0

I am looking for a bash one-liner which can cat a number of files with a number of fixed lines.

file1.txt:

file1 line 1
file1 line 2

file2.txt

file2 line 1
file2 line 2

Then I am looking for something like

cat-with-strings foo file1.txt bar file2.txt baz

producing output

foo
file1 line 1
file1 line 2
bar
file2 line 1
file2 line 2
baz

How can I do this in a single line of bash, using standard linux tools (sed, awk, cat, etc) and without creating any files to hold foo, bar, or baz?

1

Typing on my phone so apologies for a sketch, untested answer.

Surely you can just concatinate (cat) everything as if everything was a file:

cat <( echo foo ) file1.txt <( echo bar ) file2.txt <( echo baz )
1
sh -c 'while [ $# -gt 0 ] ; do echo "$1" ; cat "${2:-/dev/null}" ; shift 2 2>/dev/null; done' - foo file1 bar file2 baz

In general requiring this to be a 1-liner is pretty silly, who cares if it is one line if you put it in a shell function or file?

1

With one command using any awk in any shell on every Unix box

$ awk 'FNR==1{print x} 1; END{print x}' x='foo' file1 x='bar' file2 x='baz'
foo
file1 line 1
file1 line 2
bar
file2 line 1
file2 line 2
baz

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.