How do I double each line of input piped in?


echo "foobar" | MYSTERY_COMMAND


Just use sed p.

echo foobar | sed p

You don't need cat, either:

sed p input.txt
# or
sed p input.txt > output.txt


p is the sed command for "print."

Print is also sed's default action. So when you tell sed explicitly to print, the result is that it prints every line twice.

Let's say you wanted to only print lines that include the word "kumquat." You can use -n to supress sed's default action of printing, and then tell it explicitly to print lines that match /kumquat/:

sed -n /kumquat/p

Or if you only want to print the 5th line and nothing else:

sed -n 5p

Or, if you want to print every line from the 15th line to the 27th line:

sed -n 15,17p

If you want to print every line except lines which contain "kumquat," you could do this by just deleting all the kumquat lines, and letting sed's default action of printing the line take place on non-deleted lines. You wouldn't need the -n flag or an explicit p command:

sed /kumquat/d

sed works on a simple pattern—action syntax. In the above examples, I've shown line-number-based patterns and regex-based patterns, and just two actions (print and delete). sed has a lot more power than that.

I should really include the most common and useful sed command there is:

sed s/apples/oranges/g

This replaces every instance of "apples" with "oranges" and prints the result.

(If you omit the global flag to the substitute command, only the first instance on every line will be changed.)

Further reading (highly recommended):

  • You may wish to add what p does. – sjsam May 6 '16 at 5:01
  • 1
    @sjsam, good point; done. – Wildcard May 6 '16 at 5:31
cat input.txt | awk '1;1' > output.txt 

edit: this is joepd's less verbose version, original below

cat input.txt | awk '{print $0 "\n" $0}' > output.txt 
  • 1
    ... | awk '1;1' ... – joepd May 6 '16 at 6:35

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