How to convert rows into space-delimited line and vice versa

As part of text-file batching processing job, if you would like to convert rows into a space-delimited line, or replace spaces with line break (or newline), you can use command line utilities such as tr and awk. The tr command can perform simple character translation or deletion on input text file, while the awk utility can perform more powerful pattern scanning and processing on input file. So these tools can be quite useful in any kind of shell scripts.

To convert rows into a space-delimited line:

$ cat intput.txt
apple
mango
watermelon
orange
pineapple
kiwi
$ cat input.txt | tr "\n" " "
apple mango watermelon orange pineapple kiwi

To convert spaces to line break (newline):

$ cat intput2.txt
january february march april may
sed -e 's/\s\+/\n/g' input2.txt
january
february
march
april
may

Subscribe to Xmodulo

Do you want to receive Linux FAQs, detailed tutorials and tips published at Xmodulo? Enter your email address below, and we will deliver our Linux posts straight to your email box, for free. Delivery powered by Google Feedburner.

Leave a comment

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

Current day month ye@r *