how to replace newlines in linux using tr

I like to use sed for all my string replacements when I’m in bash or use the %s option in vim. Unfortunately, when I have to get rid of newlines, I always end up doing a macro that join lines and does an edit on them.

Now you don’t if you use the translate (tr) tool found in linux. You can use tr for other purposes by checking out the man page, but I pretty much just use it to strip out all the newlines in a text file. I simply just cat out a file and pipe it through tr to do my work:

To change all the newlines into semicolons:
cat file.txt | tr '\n' ';'
To change all the newlines into spaces:
cat file.txt | tr '\n' ' '

Just redirect the output to file if you want to save it.
Replace the newline with the number 3 and output the results to file3.txt:
cat file.txt | tr '\n' '3' > file3.txt

This entry was posted in software, tips and tagged , , , , . Bookmark the permalink.

Leave a Reply

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