I have the file in the name of file123 with the content of


i want to change the keyword passwd inside the file on particularly 1,3 line.


You can do:

sed '1,3 s/^passwd/NEW/' file123
  • 1,3 makes sed only to operate on line 1 to 3

  • s/^passwd/NEW/ substitute passwd at the start (^) with NEW, change this to meet your need. Note that although 1,3 is matching from lines 1 to 3, the Regex pattern is only matching line 1 and 3 of your sample, hence modifications are being made to those lines only

To edit the file in place, with the GNU implementation of sed:

sed -i '1,3 s/^passwd/NEW/' file123
  • 1
    you might want to clarify that 1,3 means lines 1,2,3 but that your regex ensures it works for OP's input – Sundeep Aug 29 '16 at 13:08
  • 1
    @spasic Clarified.. – heemayl Aug 29 '16 at 13:13

If you want to do a substitution on lines 1 and 3 only, you can do:

sed '
  1 b subst
  3 b subst

Or with awk:

awk 'NR == 1 || NR == 3 {sub(/string/, "replacement")}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.