Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

replace a line with another

Status
Not open for further replies.
Mar 31, 2004
151
US
Hello,

Could a line be replaced by another line in file?

Ex:

11111
22222
33333
44444


3333 should be replaced by 5555. Similarily, 3 3 3 3 should be replaced .... i.e 3rd line should be replaced by 5555. Is there something that can use NR (line number).

Thanks in advance.
 
Something like this ?
awk 'NR==3{gsub(/3/,"5",$0)}1' /path/to/input

Hope This Help, PH.
Want to get great answers to your Tek-Tips questions? Have a look at FAQ219-2884
 
Try something like this:
nawk -v new3="New third line" '{print (NR==3 ? new3 : $0)' /path/to/input

Hope This Help, PH.
Want to get great answers to your Tek-Tips questions? Have a look at FAQ219-2884
 
I am using HP-UX. Bourne shell. It says nawk not found. I tried putting it in a script using csh & ksh. It still says the same.
 
And what about this ?
awk -v new3="New third line" '{print (NR==3 ? new3 : $0)' /path/to/input

Hope This Help, PH.
Want to get great answers to your Tek-Tips questions? Have a look at FAQ219-2884
 
Is there a way to use shell variable in awk script?

Code:
#!/usr/bin/sh
file = r
Number=3
echo "`cat $filename| awk -v replace="replace" '{print NR==$Number  ? replace : $0)}'`" > $filename

The above $Number as NR, won't work. Any ideas?

Thanks in advance.
 
Try this:
Number=3
echo "`awk -v replace='replace' '{print (NR=='$Number' ? replace : $0)}' $filename`" >NewFile
Or this:
echo "`awk -v replace='replace' -v Number=3 '{print (NR==Number ? replace : $0)}' $filename`" >NewFile

Hope This Help, PH.
Want to get great answers to your Tek-Tips questions? Have a look at FAQ219-2884
 
Thanks!

This works with static text in replace' '
echo "`awk -v replace='replace' '{print (NR=='$Number' ? replace : $0)}' $CountFile`" > $CountFile

I want to replace that with $* ... shell parameters.

It gives an error with $*.
 
echo "`awk -v replace='replace' '{print (NR=='$Number' ? replace : $0)}' $CountFile`" > $CountFile
I don't think it's safe to have the same $CountFile file as stdin for awk and stdout for echo: it may be erased by the shell before awk have any chance to read it.
It gives an error with $*
Which error ? where ? can you please post the code ?

Hope This Help, PH.
Want to get great answers to your Tek-Tips questions? Have a look at FAQ219-2884
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top