Tom's Guide | Tom's Hardware | Tom's Games
![]() |
![]() |
![]() |
Hi,
I want to replace few characters based on position.
For example, I have the following string:
202204051121010000033333301000086963000000000000000000000000000000000000000000
in which the characters in 7th position to 12th are date. I want to replace the characters in 7th position to 12th position with today's date. That is replace 051121 with 051123.I will be having today's date in a variable. I need to assign that to 7th - 13th position.
Can you please let me know how to change this.
Thanks,
Anil

I think the easiest way is to cut the string at columns 1 to 6 and postion 13 to the end of the line. Then glue them back together with today's date:
#!/bin/ksh
line="202204051121010000033333301000086963000000000000000000000000000000000000000000"
l1=$(echo "$line"|cut -c1-6)
length=${#line}# build today's date
l2=$(date "+%m%d%y")l3=$(echo $line|cut -c13-${length})
newline="${l1}${l2}${l3}"
echo $newline

Wouldn't a single regex be easier?
#!/usr/bin/perl
$str = '202204051121010000033333301000086963000000000000000000000000000000000000000000';
$date = `date "+%m%d%y"`;$str =~ s/^(.{6})(.{6})(.*)$/$1$date$3/;
print $str;

Fishmonger:
Yes, it is easier if I knew perl. -)
I tried your perl script on Red Hat Linux and Solaris, and each case I had to chop the newline to get the output right:
.
$date = `date "+%m%d%y"`;
chop($date);
.Would you mind explaining the regex you used.
Thanks
Nails

It's a substitution regex; here's its break down.
^
anchors it to the beginning of the string.(.{6})
captures/puts the first 6 characters onto $1 like your first echo/cut statement(.{6})
captures the next 6 chars (the date) into $2 like your second echo/cut. Actually, since it's not being used, we don't need to capture the date into a var; we just need to do the matching.(.*)
captures the remaining chars into $3$
anchors to the end of the stringThat was the matching part, the rest just “glues” together the parts $1 $date and $3 and assigns it back to $str.
The removing of the \n from $date can be done in its assignment.
chomp($date = `date "+%m%d%y"`);
chomp only removes the newline char
chop removes any charI don't do any shell scripting, but you can use the same regex with sed, or possibly with awk.

![]() |
Any DirectoryListener in ...
|
file copy between 2 termi...
|

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.
| Ads by Google |