Sunday, March 13, 2022

[SOLVED] How do I select specific rows with sed?

Issue

In manual of sed, the page show the methods to select specific lines but in a range.
/> How can I select spcific lines which have no rules?

seq 10

For example, how can I change line 1, 3, 7 to 11?
I tried use seq 10 | sed '1s/[0-9]/10/;3s/[0-9]/10/;7s/[0-9]/10/', but this looks complex and unclear.
Is there a way to do this easier?


Solution

This might work for you (GNU sed):

printf '%ds/[0-9]/10/\n' {1,3,{7..11}} | sed -f - file

Convert the numeric sequence (by way of bash brace expansion) into a series of sed commands and pass them as stdin to the file option to a sed invocation using file as the input file.

Or as the OP might wish:

printf '%ds/[0-9]/10/\n' {1,3,{7..11}} | sed -f - <(seq 10)

Another way to write the same solution:

seq 10 | sed $(printf '%ds/[0-9]/10/;' {1,3,{7..11}})

Yet another way:

<<<"1,3,7 to 11" sed -E 's/$/,/;s/,/ba;/g;s/\s*(to|-|\.\.)\s*([0-9]+)/,\2ba;/g;s/;ba//g' |
sed -f - -e 'b;:a;s/[0-9]/10/' <(seq 10)


Answered By - potong
Answer Checked By - Candace Johnson (WPSolving Volunteer)