Operating System - HP-UX
1752795 Members
6467 Online
108789 Solutions
New Discussion юеВ

Re: Replace whole line using sed or awk

 
SOLVED
Go to solution
Ross W
Advisor

Replace whole line using sed or awk

Hi,

I need to replace an entire line that contains a certain string with another line.

Does anyone know how I could do this? If awk or sed are not the best tools to do this I am open to suggestions.

Sorry if I am duplicating, but I have been reading man pages and trawling the posts on this website for the last 2 hours.

Cheers
Ross
15 REPLIES 15
Michael Tully
Honored Contributor

Re: Replace whole line using sed or awk

Is this what you after?

$ sed 's /string/new string/g' old_filename >new_filename
Anyone for a Mutiny ?
Con O'Kelly
Honored Contributor

Re: Replace whole line using sed or awk

Hi Ross

Don't know if this is what you're after:

sed 's///' > /tmp/newfile.

Then mv the newfile over the old.

Cheers
Con
RAC_1
Honored Contributor

Re: Replace whole line using sed or awk

sed 's/string/new string/g' file > new_file
There is no substitute to HARDWORK
Ross W
Advisor

Re: Replace whole line using sed or awk

Very similar, but I need the whole line replaced, not just the search string text.

For Example:
I have a file which sometimes contains this text.

quick brown fox

and sometimes contains

slow brown fox

I want to search for "brown" and then replace the entire line.

Any ideas?

Thanks
Ross
twang
Honored Contributor

Re: Replace whole line using sed or awk

john korterman
Honored Contributor
Solution

Re: Replace whole line using sed or awk

Hi,
the slow approach:

#!/usr/bin/sh
while read LINE
do
echo "$LINE" | grep -iq brown
if [ "$?" = "0" ]
then
echo "Replaced line"
else
echo "$LINE"
fi
done <$1


regards,
John K.
it would be nice if you always got a second chance
Ionut Grigorescu_2
Super Advisor

Re: Replace whole line using sed or awk

awk '{x=0;for(i=1;i<=NF;i++){if($i ~ /brown/) print "new line/string";x=1;break}};if (x==0) print $0}' your_file > new_file
If it weren't for STRESS I'd have no energy at all
Caesar_3
Esteemed Contributor

Re: Replace whole line using sed or awk

Hello!

Script on perl:

#!/usr/bin/perl
open (FD, "SRC_FILENAME");
open (FDN, ">TRGET_FILENAME");

foreach ()
{
if (/STRING_FOR_REPLACE/)
{
print FDN "NEW_STRING_LINE";
}
else
{
print FDN "$_";
}
}

close (FDN);
close (FD);
#END

Caesar
Rolf Modin
Advisor

Re: Replace whole line using sed or awk

awk ' toupper($0) ~ /BROWN/ {print "new row"}'

I should think this would do what I expect You to ask for.

If brown exist anyware in the input row, case independent, the whole input line is replaced by a new standard row.