Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenate strings, files and program output in Bash

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

like image 232
Boldewyn Avatar asked Jun 08 '12 11:06

Boldewyn


People also ask

How do you concatenate strings in bash?

As of Bash version 3.1, a second method can be used to concatenate strings by using the += operator. The operator is generally used to append numbers and strings, and other variables to an existing variable. In this method, the += is essentially shorthand for saying "add this to my existing variable".

How do you concatenate in a script?

String concatenation is the process of appending a string to the end of another string. This can be done with shell scripting using two methods: using the += operator, or simply writing strings one after the other.

How do I combine multiple strings into one?

Concatenation is the process of appending one string to the end of another string. You concatenate strings by using the + operator. For string literals and string constants, concatenation occurs at compile time; no run-time concatenation occurs. For string variables, concatenation occurs only at run time.


3 Answers

This works:

cat 1.css <(echo "FOO") <(sed ...) 2.css <(echo "BAR") 
like image 121
Dennis Williamson Avatar answered Sep 30 '22 08:09

Dennis Williamson


You can do:

echo "$(command 1)" "$(command 2)" ... "$(command n)" > outputFile 
like image 38
nhahtdh Avatar answered Sep 30 '22 09:09

nhahtdh


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)

like image 28
Joni Avatar answered Sep 30 '22 10:09

Joni