Ravichandra
Ravichandra

Reputation: 2352

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

Upvotes: 11

Views: 16589

Answers (2)

rohitkulky
rohitkulky

Reputation: 1232

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

Upvotes: 1

potong
potong

Reputation: 58578

This might work for you:

sed -i '2s/hi/Hello/' file

Upvotes: 22

Related Questions