1752790 Members
6278 Online
108789 Solutions
New Discussion юеВ

Anyone for scripting?

 
Adam Noble
Super Advisor

Anyone for scripting?

I imagine one of you guys will be able to solve my problem very quickly (i hope). I need a script to take a line of input and change the 5-7th character of that input and replace it with 3 alternate characters. I thought tr may be the tool to do this however can't seem to determine the specific format.
6 REPLIES 6
Robin Wakefield
Honored Contributor

Re: Anyone for scripting?

Hi Adam,

Using sed:

% echo abcdefghijkl | sed 's/\(^....\)...\(.*\)/\1zzz\2/'
abcdzzzhijkl
%

rgds, Robin
G. Vrijhoeven
Honored Contributor

Re: Anyone for scripting?

Hi,

for i in `cat file`
do
VAR=`echo $i | cut -c 5-7`
echo $i | sed 's/'$VAR'//'
done

Gideon

Jean-Louis Phelix
Honored Contributor

Re: Anyone for scripting?

Hi,

sed 's;^\(....\)...;\1ABC;' file

should replace 5th, 6th and 7th chars to ABC.

Regards
It works for me (┬й Bill McNAMARA ...)
Adam Noble
Super Advisor

Re: Anyone for scripting?

Thanks guys much appreciated, even tho the sed command looks a little complex, I think I see what going on.
Marcin Piwko
Advisor

Re: Anyone for scripting?

This is better than sed:

nawk '{ print substr($0, 1, 4) "XXX" substr($0, 8) }' filename

Where XXX are your alternate characters.
Jean-Louis Phelix
Honored Contributor

Re: Anyone for scripting?

Perhaps awk would be more 'readable':

awk '{
printf "%s%s%s\n", substr($0,1,4),
"ABC",
substr($0, 8)}'
}' file

will do the same ...

Regards.
It works for me (┬й Bill McNAMARA ...)