How to join a list with proper delimiter using shell script & tools?
E.g., given,
$ seq 3
1
2
3
The seq 3 | list_join
will produce 1,2,3
, without the trailing ,
.
The seq
is just a sample input, the actual input can come from anywhere and there should be no assumption on the input content/format except each ends with a new line.
UPDATE:
I asked for "shell script & tools" so I'm accepting the current shell script solution, although I personally would use Fravadona's solution:
$ jot -w 'Entry %c' 5 'A' | tee /dev/tty | paste -s -d ','
Entry A
Entry B
Entry C
Entry D
Entry E
Entry A,Entry B,Entry C,Entry D,Entry E
CodePudding user response:
For a single-character delimiter, a fairly easy way would be to gather the items into an array, then expand the array with IFS
set to the delimiter.
For example, for input in the form of lines read from the standard input, with the result written to the standard output, you could do this:
list_join() {
local IFS
local -a items
mapfile -t items
IFS=,
printf %s "${items[*]}"
}
Demo:
$ seq 3 | list_join
1,2,3
$
The same technique is applicable to input from other sources and output to other destinations, though the details (mapfile
/ printf
) would need to be adjusted. The essentials are IFS
and the array expansion ("${items[*]}"
).