How can I join multiple lines into one line, with a separator where the new-line characters were, and avoiding a trailing separator and, optionally, ignoring empty lines?
Perhaps a little surprisingly, paste
is a good way to do this:
paste -s -d","
This won't deal with the empty lines you mentioned. For that, pipe your text through grep
, first:
grep -v '^$' | paste -s -d"," -
How about to use xargs?
for your case
$ cat foo.txt | sed 's/$/, /' | xargs
Be careful about the limit length of input of xargs command. (This means very long input file cannot be handled by this.)
My answer is:
awk '{printf "%s", ","$0}' foo.txt
printf
is enough. We don't need -F"\n"
to change field separator.