Remove/replace line break in bash output

Sometimes it’s much more convenient (or required) to feed a list as one line with separated elements instead of one item per line. Example:

You have this (just a random list of files):

You want this:

Tools like ls and echo have their own parameters to handle this individually, but I found two simple solutions that work for ALL bash output: one makes use of tr and the other of xargs. The latter makes sense if you want the list of elements as command line parameters for another tool (i.e. open all *.c files in this directory in a text editor) while tr is useful if you want to pipe the list to another program or into a file.

xargs

tr

ls | grep “\.c$” | tr ‘\n’ ‘ ‘

In this example tr takes the input and replaces each new line character ('\n') with a space character (' '). tr has a few interesting options to manipulate output. The description from the man page pretty much sums it up:

“Translate, squeeze, and/or delete characters from standard input, writing to standard output.”

Found in this reply on Ask Ubuntu by user roadmr.

Leave a Reply

Your email address will not be published. Required fields are marked *