25

The use case is, in my case, CSS file concatenation, before it gets minimized. To concat two CSS files:

cat 1.css 2.css > out.css

To add some text at one single position, I can do

cat 1.css <<SOMESTUFF 2.css > out.css
This will end in the middle.
SOMESTUFF

To add STDOUT from one other program:

sed 's/foo/bar/g' 3.css | cat 1.css - 2.css > out.css

So far so good. But I regularly come in situations, where I need to mix several strings, files and even program output together, like copyright headers, files preprocessed by sed(1) and so on. I'd like to concatenate them together in as little steps and temporary files as possible, while having the freedom of choosing the order.

In short, I'm looking for a way to do this in as little steps as possible in Bash:

command [string|file|output]+ > concatenated
# note the plus ;-) --------^

(Basically, having a cat to handle multiple STDINs would be sufficient, I guess, like

<(echo "FOO") <(sed ...) <(echo "BAR") cat 1.css -echo1- -sed- 2.css -echo2-

But I fail to see, how I can access those.)

Boldewyn
  • 81,211
  • 44
  • 156
  • 212

3 Answers3

34

This works:

cat 1.css <(echo "FOO") <(sed ...) 2.css <(echo "BAR")
Dennis Williamson
  • 346,391
  • 90
  • 374
  • 439
  • 1
    D'oh! That's the simplest solution (in my case), so I'll accept this. – Boldewyn Jun 08 '12 at 12:05
  • 2
    Of course @Boldewyn must've added `> concatenated.css` or `| compiler` at the end for it to work for his problem like this: `cat file1.css <(echo "FOO") <(command [string|file|output]) file2.css <(echo "BAR") > concatenated` – hobs Mar 15 '13 at 20:29
21

You can do:

echo "$(command 1)" "$(command 2)" ... "$(command n)" > outputFile
nhahtdh
  • 55,989
  • 15
  • 126
  • 162
17

You can add all the commands in a subshell, which is redirected to a file:

(
    cat 1.css
    echo "FOO"
    sed ...
    echo BAR
    cat 2.css
) > output

You can also append to a file with >>. For example:

cat 1.css  >  output
echo "FOO" >> output
sed ...    >> output
echo "BAR" >> output 
cat 2.css  >> output

(This potentially opens and closes the file repeatedly)

Joni
  • 108,737
  • 14
  • 143
  • 193
  • You can use a curly brace block to do the same thing. – Dennis Williamson Jun 08 '12 at 11:25
  • Thanks. Yes, that'd do it, completely missed that option. +1. – Boldewyn Jun 08 '12 at 12:06
  • If I am not mistaken, () is POSIX-compliant, whereas command-substitution is a bash extension, which was unimplemented in Cygwin Bash until about 2008. – Leo Jan 07 '14 at 17:41
  • 1
    @Leo, you are mistaken. Command substitution is absolutely specified in POSIX sh; see http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_03 – Charles Duffy Sep 24 '17 at 03:33