Operating System - HP-UX
1752800 Members
5616 Online
108789 Solutions
New Discussion юеВ

Re: Change occurrence of a string in shell

 
Jean-Luc Oudart
Honored Contributor

Re: Change occurrence of a string in shell

Awk solution :

#!/bin/sh

awk '{
if(substr($0,4,3)=="XXX") {
printf("%s%s%s\n",substr($0,1,3),"YYY",substr($0,7));
} else print;}'

or shorter
awk '{ if(substr($0,4,3)=="XXX") printf("%s%s%s\n",substr($0,1,3),"YYY",substr($
0,7)); else print; }'

Regards,
Jean-Luc
fiat lux
Rodney Hills
Honored Contributor

Re: Change occurrence of a string in shell

Procura,

Cool- I didn't even think about substr being usable as an lvalue...

-- Rod Hills
There be dragons...
Muthukumar_5
Honored Contributor

Re: Change occurrence of a string in shell

If you want to change the first occurence of XXX with YYY then,

echo "123XXX789XXX" | sed -e 's/XXX/YYY/1'
or
echo "123XXX789XXX" | sed -e 's/XXX/YYY/'

It will only change the first XXX with YYY
To change the next occurence with YYY then,

echo "123XXX789XXX" | sed -e 's/XXX/YYY/2'
To all,
echo "123XXX789XXX" | sed -e 's/XXX/YYY/g'


Regards
Muthu
Easy to suggest when don't know about the problem!
Muthukumar_5
Honored Contributor

Re: Change occurrence of a string in shell

We can do checking and replacing as,
[[ "$(echo "123XXX789XXX" | cut -c 4-6)" = "XXX" ]] && echo "123XXX789XXX" | perl -pe 's/^(...)XXX/$1YYY/'

or as,

VAR="123XXX789XXX"
[[ "$(echo $VAR | cut -c 4-6)" = "XXX" ]] && VAR=$(echo $VAR | perl -pe 's/^(...)XXX/$1YYY/')

echo $VAR
Easy to suggest when don't know about the problem!
Elmar P. Kolkman
Honored Contributor

Re: Change occurrence of a string in shell

Rodney's perl solution works with sed too, of course.

sed 's|^\(...\)XXX|\1YYY|' file

As for the remark 'can be the first occurrence or not' I think Diego meant that it is possible that there are X characters in the first 3 characters of the line, resulting in problems with the first two solutions.
Every problem has at least one solution. Only some solutions are harder to find.