Using SED to replace newlines with commas

In the Linux world it is often necessary to manipulate data from commands in text form. Here’s a quick and easy way, using sed, to search for newlines in your output and insert commas where needed. This can be particularly useful if you intend on piping your output to an array for a script.




# sed -n ‘1h;2,$H;${g;s/\n/,/g;p}’ file.txt

Pretty ugly huh? That will get the job done with little effort. If you wish to replace the newlines in the file just use the -i flag with sed and your file will automagically be updated.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.