panyam
1
Hi all ,
Recently i came across this in FAQ's.
I have a file
cat rem.txt
sreedhar 20
sreedhar 10
sreedhar 15
sreedhar 18
sreedhar 16
sreedhar 30
I have to replace sreedhar with "Sridhar" if the second parameter is > 18.
I need to do it in "sed" only. I am wondering how this can be done.
zaxxon
2
If you have gsed you can use egrep like syntax for matching multiple strings, ie.
(pattern1|pattern2|...)
If you want to stay compatible you can use:
sed -e '/ 19$/ {s/sreedhar/Sridhar/}' -e '/ [2-9][0-9]\+$/ {s/sreedhar/Sridhar/}' infile
Sridhar 20
sreedhar 10
sreedhar 15
sreedhar 18
sreedhar 16
Sridhar 30
In awk this would have been much easier and also with real arithmetics.
panyam
3
Thanks zaxxon for the solution.
But it's not working as i am getting the error
Function / 19$/ { s/sreedhar/Sridhar/ } cannot be parsed.
Yes , i worked with awk and it's easy to do it in awk.
But sed's solution is seems to be cumbersome as we are not doing much like arithmetic operations.
With a little modification to above script, you can do this...
sed -n '
/ 19$/ {
s/sreedhar/Sridhar/
p
}
/ [2-9][0-9]$/ {
s/sreedhar/Sridhar/
p
}' file
---------- Post updated at 07:02 PM ---------- Previous update was at 07:00 PM ----------
If the number is negative or greater than 99... We need to tweak a bit more.
panyam
5
Thanks Rakesh ...
I tried in the same way ,but .. As i was messing "-e" with "-n" there were some errors i was getting.
sed always makes me "sad"