Operating System - HP-UX
1755320 Members
4089 Online
108831 Solutions
New Discussion юеВ

Replace whole line using sed or awk

 
SOLVED
Go to solution
Rolf Modin
Advisor

Re: Replace whole line using sed or awk

Hm...

awk ' toupper($0) ~ / BROWN[\.,!? ]/ {print "new row"}' input > output

This version acts only when 'brown' is used as a sepatate word, and not for instnace as 'brownies'. It accepts ".", ",", "!", "?" and " " as the character after 'brown'.


Stephen Day
Occasional Advisor

Re: Replace whole line using sed or awk


A nice simple approach:

Say the string you are looking for is STRING_TO_BE_REPLACED.
And the line you want to insert is LINE_TO_REPLACE_WITH.
The input file is 'file', the output file is 'new_file':

cat file | sed 's/^.*STRING_TO_BE_REPLACED.*$/LINE_TO_REPLACE_WITH/' >new_file

The ^ is a start of line anchor, the '.*' is a wildcard, the $ is a end of line anchor.

Personally I think this looks a lot cleaner than most of the other ways to do this I've seen here.

It was like that when I got here.
Rolf Modin
Advisor

Re: Replace whole line using sed or awk

shame on me!

This is how it works well:

awk '{if(toupper($0) ~ / BROWN[;\.,!? ]/) {print "new row"} else {print $0}}' input


The text "brown" will trigger a complete different standard line to be printed instead of the line "brown" is found in. But the line will only be replaces if "brown" begins with a space, and if the character after "brown" is one of ";.,!?" or space. The check will ignore case.

If it looks like "[" or "]" that should be replaces with sqare brackets instead.
Rolf Modin
Advisor

Re: Replace whole line using sed or awk

shame on me!

This is how it works well:

awk '{if(toupper($0) ~ / BROWN[;\.,!? ]/) {print "new row"} else {print $0}}' input


The text "brown" will trigger a complete different standard line to be printed instead of the line "brown" is found in. But the line will only be replaced if "brown" begins with a space, and if the character after "brown" is one of ";.,!?" or space. The check will ignore case.

If it looks like "[" or "]" that should be replaces with sqare brackets instead.
Robert Salter
Respected Contributor

Re: Replace whole line using sed or awk

You could put it in a script if you have to do this more than once using a couple of different variables i.e;

# file1 contains line to insert
REPLN=`cat file1`
# or set the variable with the line to be #inserted
REPLN="dumb ol fox"

sed "s/^.*$2.*$/$REPLN/ $1 > $1.a
mv $1.a $1 # overwrite the original file

run it
swtchln.sh myfile brown

course there's lots of mods you can make to this, but you get the gist of it.
Time to smoke and joke
Ross W
Advisor

Re: Replace whole line using sed or awk

close