0

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
xpt
  • 16,540
  • 26
  • 100
  • 179
  • 3
    `seq` knows the option `-s`: `seq -s "," 3` – leu Jun 04 '22 at 15:39
  • 4
    `seq 3 | paste -s -d ','` will join each _line_ with `,` – Fravadona Jun 04 '22 at 15:41
  • `echo {1..3}|tr ' ' ','` – ufopilot Jun 04 '22 at 15:45
  • @ leu / ufopilot seq is just a sample input, the actual input can come from anywhere, that's why I upvoted Fravadona's solution. – xpt Jun 04 '22 at 15:50
  • Does this answer your question? [How to concatenate multiple lines of output to one line?](https://stackoverflow.com/questions/15580144/how-to-concatenate-multiple-lines-of-output-to-one-line) – pjh Jun 04 '22 at 19:31
  • @pjh, that's really an odd requirement, asking for replacing each "\n" with "\" " (end with " followed by space). I have never ever need to do that. – xpt Jun 04 '22 at 20:55
  • @xpt, most of the answers to that question directly address your requirement. The majority use space as the separator, but some use comma. Most of the answers are easy to modify to use other separators. Other effective duplicates include [Concise and portable "join" on the Unix command-line](https://stackoverflow.com/q/8522851/4154375), [How to join multiple lines of file names into one with custom delimiter?](https://stackoverflow.com/q/2764051/4154375), and [Turning multiple lines into one comma separated line](https://stackoverflow.com/q/15758814/4154375). – pjh Jun 04 '22 at 23:47
  • @xpt, there's also [Turning multi-line string into single comma-separated](https://stackoverflow.com/q/8714355/4154375). – pjh Jun 04 '22 at 23:54

1 Answers1

0

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[*]}").

John Bollinger
  • 138,022
  • 8
  • 74
  • 138