Mak
Mak

Reputation: 121

How to add more than one delimiter in Bash

I'm trying to figure out how to set two delimiters: one is newline and another one is space so when I read numbers from file that is filled like this

1 2 3
4
5 
6

I get one number by order like 1,2,3,4,5,6. I'm using read command to read numbers. Thanks!

Upvotes: 1

Views: 586

Answers (1)

James Brown
James Brown

Reputation: 37424

Your question is pretty unclear but based on the sample and expected output the trivial solution would be to use tr:

$ cat file | tr '[ \n]' ,
1,2,3,4,5,,6,

but there is a space after 5 so you need to use -s to squeeze the repeats:

$ cat file | tr -s '[ \n]' ,
1,2,3,4,5,6,

which still leaves you with a nasty trailing comma and a missing newline from the end. That can be handled with sed or awk. (with Sapphire and Steel narrator's voice) Awk has been assigned:

$ cat file | tr -s '[ \n]' , | awk 'sub(/,$/,"")' # fails if output is just 0
1,2,3,4,5,6                                       # add ||1 or ||$0!="" to fix

Wait. Since we started awk why bother with the tr at all:

$ awk '{
    gsub(/ +/,",",p)            # replace space runs with a single comma
    printf "%s",p
    p=(p~/,$/||NR==1?"":",") $0 # 5 followed by space leaves a comma in the end so...
}
END {
    print p
}' file
1,2,3,4,5,6

Well that turned out looking complicated and I just now noticed you did mention using the read command so maybe I'm way off with my solutions and I should've used bash scripting from the beginning:

s=""                     # using this neat trick I just learned here ;D
while read line          # read a full line
do 
    for word in $line    # read word by word
    do 
        echo -n $s$word  # output separator and the word
        s=,              # now set the separator 
    done
done < file
echo                     # newline to follow
1,2,3,4,5,6

Yes, it is Saturday evening and I have no life.

Upvotes: 1

Related Questions