2

I do know how to replace a string from a specific line such as:

sed -i "<line number>s/<old string>/<new string>/g" <file name>

however I do not know how to replace a string from multiple lines for example from a line number 1 then 10 and then 100

  • sed doesn't support substitution by set of arbitrary numbers – RomanPerekhrest Dec 8 '18 at 21:33
4

As far as I know, sed addresses may only consist of a single line, or a range of lines.

However you could cobble something together using sed -f - to read commands from standard input, together with your shell. For example:

  printf '%ds/<old string>/<new string>/g\n' {1,10,100} | sed -f - file
  • Brilliant solution. Alternative to avoid the pipe: sed -f <(printf '%ds/line/LINE/g\n' {1,10,100}) file1 – George Vasiliou Dec 9 '18 at 17:36
3

Here is an awk answer.

awk 'NR == 1 || NR == 10 || NR == 100 {gsub(/old/,"new")}; {print}' <file name>

Explanation

  • NR == 1 || NR == 10 || NR == 100: only do the following commands on one of these lines.
  • gsub(/old/,"new"): substitute /old/ with new.
  • {print}: regardless of what line you are on, print the line.
1

An alternative directly with sed:

 sed '1b1; 10b1; 100b1; b ;:1;s/<old string>/<new string>/g' <file name>

If the line number matches either 1, 10, or 100, branch to label 1; on other lines, just branch to the end (which, by default, prints the line).

somewhat automated:

 sed -e $(printf '%sb1;' 1 10 100) -e 'b; :1;s/<old>/<new>/g' <file name>

POSIXly (with default IFS):

 sed $(printf -- '-e %sb1 ' 1 10 100) -e 'b' -e':1' -e 's/<old>/<new>/g'
0

Well, how about:

sed -e '
     /something_identifying_startline/,/something_identifying_endline/{
        s/dog/cat/
        s/black/white/
        }
  • Welsome to U/L and thanks for posting an answer. However, this won't let you select multiple ranges (nor select by line number). – Sparhawk Dec 8 '18 at 22:03

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.