Thursday, June 23, 2016

Concatenate in bash the output of two commands without newline character

I'm working on a bash script and I needed to import some data that I've compressed. However, the tables could also have foreign key constraints that I want ignored. So as I'm importing the dump files, I add "SET FOREIGN_KEY_CHECKS=0" to the file like this:

       { echo "SET FOREIGN_KEY_CHECKS=0;" ; gunzip < my_dump_file.sql.gz ; } | mysql -u${USERNAME} -p${PASSWORD} -h${SERVER} ${DATABASE} 

Found a good example on stackoverflow which taught me how to do this:

Reference:

http://stackoverflow.com/questions/20871534/concatenate-in-bash-the-output-of-two-commands-without-newline-character

Question:

What I need:
Suppose I have two commands, A and B, each of which returns a single-line string (i.e., a string with no newline character, except possibly 1 at the very end). I need a command (or sequence of piped commands) C that concatenates the output of commands A and B on the same line and inserts 1 space character between them.

Answer:

You can use tr:
{ echo "The quick"; echo "brown fox"; } | tr "\n" " "
OR using sed:
{ echo "The quick"; echo "brown fox"; } | sed -e 'N;s/\n/ /'

OUTPUT:

The quick brown fox 




No comments:

Post a Comment