Replacing a string in nth line a file

12,829

Solution 1

This might work for you:

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

Solution 2

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
Share:
12,829
Ravichandra
Author by

Ravichandra

Engineer by education. "Make work Easy " by nature

Updated on July 02, 2022

Comments

  • Ravichandra
    Ravichandra almost 2 years

    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