echo '1,2,3,5' | sed -n data.txt

which gives

sed: 1: "data.txt": extra characters at the end of d command

I want to give linenumbers for search from other command. Actually awk is giving those numbers from this thread.


this line 3
and here we go 4
and 5 is here

where output should be

this line 3
and 5 is here

How can you give sed those linenumbers?


Basically you can do something like

eval $(echo sed $(for i in 1 2 3 5; do echo "-e ${i}p"; done) -n data.txt )

To read the line numbers from a file containing the numbers, separated by space, use

eval $(echo sed $(for i in $(< line-numbers.txt); do echo "-e ${i}p"; done) -n data.txt )

In this case, you can use any command which produces a list of line number instead of the < line-numbers.txt part.

Or, if the numbers in the file are separated by ,

eval $(echo sed $(for i in $(tr \, ' ' < line-numbers.txt); do echo "-e ${i}p"; done) -n data.txt )

(and again, the command can be anything producing line numbers separated by ,)

  • Any better idea how to do this better? I am really open to any innovation. To get linenumbers from a command and give them to Sed. – Léo Léopold Hertz 준영 Jun 15 '15 at 13:50
  • How do say i in [numbers-in-file]? I tried i in data.txt unsuccessfully, also unsuccessfully i in `cat data.txt`. data.txt here 1,2,3. – Léo Léopold Hertz 준영 Jun 15 '15 at 13:55
  • data.txt contains the text, doesn't it? You can do for i in $(cat line-numbers.txt); do but this requires the numbers to be separated by space, not by comma. – nohillside Jun 15 '15 at 13:58
  • 1
    or use $(cat line-numbers.txt | tr , ' ') to replace comma by space. – nohillside Jun 15 '15 at 13:59

Another way is using sed with xargs.

echo '1p;2p;3p;5p' filename | xargs sed -n

Basically sed uses the format <line-number>p to display a line. You can separate several lines using ;.

  • and assuming you can't change the input you can do echo 1,2,3,5|sed -e 's/,/p;/' -e 's/$/p filename/'|xargs sed -n – hildred Jun 15 '15 at 19:31

Assuming the output from your awk command is 1,2,3,5, you can do this:

sed -n $(my_awk_commamd | sed 's/,/p;/g;s/$/p;/') data.txt

The sed inside the $( command substitution converts 1,2,3,5 to the sed expression 1p;2p;3p;5p;, which is then interpreted by the outer sed over the data file.

A unit test, replacing awk with a simple echo:

$ sed -n $(echo '1,2,3,5' | sed 's/,/p;/g;s/$/p;/') data.txt 
this line 3
and 5 is here

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .