Operating System - HP-UX
1752790 Members
6378 Online
108789 Solutions
New Discussion юеВ

sed - print old line and new changed line

 
SOLVED
Go to solution
Billa-User
Regular Advisor

sed - print old line and new changed line

hello,

i have a file "TEST" and want to change the digit(s) after "=" . but i also want to print the old entry with a comment (for information).
i want to use "sed", is it possible ?

file:
TEST = 10 # comment default value: 0

sed , with "p" , i can print the old entry, but i want to change it with "#"

sed -e "/^\([ \t]*TEST[ \t]*=[ \t]*\)/ {
p
s/^\([ \t]*TEST[ \t]*=[ \t]*\)\([0-9]*\)\([ \t]*\)/\199\3/p
}" TEST

the new output should be:
#TEST = 10 # comment default value: 0
TEST = 99 # comment default value: 0

regards,tom
4 REPLIES 4
James R. Ferguson
Acclaimed Contributor

Re: sed - print old line and new changed line

Hi Tom:

I'd use Perl:

# perl -pe '$match=qr{(.*TEST\s*=\s*)(10\b)};m{$match} and print and s{10}{99}' file

Regards!

...JRF...
Dennis Handly
Acclaimed Contributor
Solution

Re: sed - print old line and new changed line

>I want to use sed(1), is it possible?

Yes, but it requires work, where perl and awk it would be more obvious.
================================================
sed '
/^\([ \t]*TEST[ \t]*=[ \t]*\)/ {
h; # save
s/^/#/
p
g; # restore
s/^\([\t]*TEST[\t]*=[\t]*\)\([0-9]*\)\([\t]*\)/\199\3/
} ' TEST > TEST.new

Note you can't really use \t for a tab.
I had to remove the space on the last "s" line so it wouldn't break.
James R. Ferguson
Acclaimed Contributor

Re: sed - print old line and new changed line

Hi (again) Tom:

Actually, this variation is a bit "safer" insofar as it avoids potentially superious substitutions:

# perl -pe '$match=qr[(.*TEST\s*=\s*)(10)(\b)];m[$match] and print and s[$qr][${1}99]' file

Regards!

...JRF...
Billa-User
Regular Advisor

Re: sed - print old line and new changed line

hello dennis,

thanks a lot for your "sed" solution and i use following character [:space:] for whitespace/blank. I hope that was also in your interest. now "sed" works well.

sed '
/^\([[:space:]]*TEST[[:space:]]*=[[:space:]]*\)/ {
h; # save
s/^/#/
p
g; # restore
s/^\([[:space:]]*TEST[[:space:]]*=[[:space:]]*\)\([0-9]*\)\([[:space:]]*\)/\199\3/
} ' TEST > TEST.new

regards,tom