EDIT:
Perhaps my favorite method nowadays is to use a special character instead of '\ n'. Citation rules become such a headache when you walk around a line. But if you pack your string, say | instead of \n and _ instead , then you have a truly portable representation that you can pass into functions, etc.
Here is an example:
whatAmI=$( printf "Wow oh wow\nYou are good\n"| \ sed -e 's#\(You are \)\(good\)#\1\2|\1the best#g' | \ tr '\n' '|' | tr ' ' '_' )
Result:
Wow_oh_wow | You_are_good | You_are_the_best |
To "unzip" your compressed line, simply pass it through the same tr , but with the reversal of the order.
i.e.
echo "$whatAmI" | tr '|' '\n' | tr '_' ' '
Result
Wow wow
You're good
You are the best
In addition to the above strategies (using appen - /a and splitting with \\\n ) you can also do this:
sed -i 's/You are good/You are good'"\n"' You are the best/g' /output.txt
In some ways, I prefer Glenn Jackman's decision, as it is more true to intent.
But I find this strategy useful, as you can also use it to pass in variables in bashscripts. If you are not going to use the variable more than once, it will be cleaner than -v , for example.
whatYouAre="okay" sed -i 's/You are good/You are good'"\n"' You are '"${whatYouAre}"'/g' /output.txt
(Note: single quotes also work for \n , but not for passing to vars, as this requires interpretation.)
Jason R. mick
source share