Concise and portable “join” on the Unix command-line

前端 未结 9 1969
囚心锁ツ
囚心锁ツ 2020-11-29 00:53

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?

9条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-29 01:10

    Just for fun, here's an all-builtins solution

    IFS=$'\n' read -r -d '' -a data < foo.txt ; ( IFS=, ; echo "${data[*]}" ; )
    

    You can use printf instead of echo if the trailing newline is a problem.

    This works by setting IFS, the delimiters that read will split on, to just newline and not other whitespace, then telling read to not stop reading until it reaches a nul, instead of the newline it usually uses, and to add each item read into the array (-a) data. Then, in a subshell so as not to clobber the IFS of the interactive shell, we set IFS to , and expand the array with *, which delimits each item in the array with the first character in IFS

提交回复
热议问题