Hi
My input file is like this for eg:
abc abc abc abc abc abc
i would like to replace "abc" with "cba" where the occurrence is divisible by 2
of eg here 2nd, 4th and 6th occurence shud be replace
can anyone suggest in awk or sed
Hi
My input file is like this for eg:
abc abc abc abc abc abc
i would like to replace "abc" with "cba" where the occurrence is divisible by 2
of eg here 2nd, 4th and 6th occurence shud be replace
can anyone suggest in awk or sed
echo "abc abc abc abc abc abc"|sed -e "s/abc abc/abc cba/g"
abc cba abc cba abc cba
Given your sample data this should work:
awk '{ for (i=1; i<=NF; i++)
$i = i % 2 ? $i : "cba"
}1'
Be aware that the above code will squeeze consecutive FS characters.
With Perl:
perl -pe's/(\w+)/$c++%2?cba:$1/ge'
% print abc abc abc abc abc abc |
awk '{ for (i=1; i<=NF; i++)
$i = i % 2 ? $i : "cba"
}1'
abc cba abc cba abc cba
% print abc abc abc abc abc abc |
perl -pe's/(\w+)/$c++%2?cba:$1/ge'
abc cba abc cba abc cba
---------- Post updated at 02:45 PM ---------- Previous update was at 02:45 PM ----------
Nice
Hi thax for the reply but im making an example since in my requirements its 25rd every occurence i need to replace in a line
Another one :):
echo 'abc abc abc abc abc abc'|
awk '{for(i=2;i<=NF;i+=2){$i="cba"}}1'
Or:
awk '{
for (i=2; i<=NF; i+=2)
$i = "cba"
}1'
Edit: Just saw it was already posted.
Thanks for the reply i need to match "abc" within other patterns also
like
abc bbb bbb abc bbb ccc abc
so need to match the pattern and occurence too
Could you give an example?
eg:
val1 | val2 | val1 | val2 | val1 | val2 | val1 | val2
here i need to replace '|' with '|\n' where the occurence of '|' is divisble by 2
I still don't understand what exactly you want to match.
If Perl is acceptable:
% print 'val1 | val2 | val1 | val2 | val1 | val2 | val1 | val2' |
perl -pe's/(\| )/$c++%2?"$1\n":$1/ge'
val1 | val2 |
val1 | val2 |
val1 | val2 |
val1 | val2
S that was the requirment
But now in my real use it is after every 25th occurence of '|' in a line i need to place a '\n'
For eg
i have 75 occurence of '|' in a line, so i have to replace the 25th,50th and 75th occurence of '|' with '|\n'
when i used perl -pe's/(\| )/$c++%25?"$1\n":$1/ge'
it did not work
perl -pe's/(\| )/++$c%25?$1:"$1\n"/ge'