I recently was having to work with Ansible for several days to deploy changes globally across prod. I was storing my playbook limit in a file like so:

[18:45] james_simas@widget ~/Downloads $ cat limit.txt
host1.domain.com
host2.domain.com
host3.domain.com

At one point, I needed to use supply the list of hostnames in BASH, but rather than having them be newline separated, I needed them to be separated by commas like this:

host1.domain.com,host2.domain.com,host3.domain.com

I didn’t want to modify my original files (I still needed them) and this seemed like a problem somebody else has problably solved. I Googled a bit and found an answer using tr.

I hadn’t used tr much before, but it turned out to be incredibly easy.

Here’s me using it to change the newlines in my file to commas.

[18:45] james_simas@widget ~/Downloads $ cat limit.txt | tr '\n' ','
host1.domain.com,host2.domain.com,host3.domain.com,

You can go the other way (comma to newline) just as easily:

[18:46] james_simas@widget ~/Downloads $ cat limit.txt | tr '\n' ',' | tr ',' '\n'
host1.domain.com
host2.domain.com
host3.domain.com
[18:46] james_simas@widget ~/Downloads $