Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing a string in nth line a file

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

like image 798
Ravichandra Avatar asked Sep 01 '15 06:09

Ravichandra


2 Answers

This might work for you:

sed -i '2s/hi/Hello/' file
like image 141
potong Avatar answered Sep 24 '22 05:09

potong


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
like image 40
rohitkulky Avatar answered Sep 25 '22 05:09

rohitkulky