How to Replace Newlines With Commas in CLI


If you need to replace all newline characters with a comma, or perhaps some other delimiter, then using the build-in tr utility will work very well for you.

Possible use-cases for this is if you need to transport a configuration file with multiple lines into a single input field, or store the file’s contents within an environment variable.

My personal use-case was to store an ~/.aws/credentials file in an environment variable.

Your solution using tr

tr '\n' ',' < input.txt > output.txt

How this works

tr is branded as a translate or delete characters command-line tool.

The first argument is the string to find, while the second is the string to replace with.

< indicates the input file ingested into tr, while the > indicates where the output will be piped to.

In our example above, we take an input.txt file, apply a \n->, conversion, then push the result to an output.txt file.

If the output.txt file does not exist, it will create it.