To give STDIN for Sed?

Solution 1:

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 ,)

Solution 2:

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 ;.

Solution 3:

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 
hello 
amigo
this line 3
and 5 is here
$