Hi need to replace a string in file only in nth line of file
file1
hi this is line 1
hi this is line 2
hi this is line 3
hi this is line 4
I need to replace 'hi' only in line 2
experted as below
hi this is line 1
Hello this is line 2
hi this is line 3
hi this is line 4
I tried by creating a temp file
sed -n 2p file1 > temp1
perl -pi -e 's/hi/Hello/g' temp1 \\I tried to replace temp1 with line 2 in file1
sed -i '2d' file1 \\after this I failed to insert temp1 as a 2nd line in file1
Help me to replace a string in file in Nth line(without temp file is preferred.. ).
Thank you
This might work for you:
sed -i '2s/hi/Hello/' file
Above answer is correct, but I am tempted to put AWK variant just for reference.
awk 'NR==2{gsub("hi","Hello",$1)}; {print $0}' file > newfile
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With