Exploring
Exploring

Reputation: 3369

How to concatenate all lines of a file from ant script?

I have a text file in the following format:

cat yourfile.txt
a
b
c
d
e
f
g

I want to convert it to:

a,b,c,d,e,f,g

This is the solution I came up to now:

while read line; do printf "%s%s" $line "," ; done < yourfile.txt
a,b,c,d,e,f,g,

Two issues:

Upvotes: 2

Views: 219

Answers (3)

Idriss Neumann
Idriss Neumann

Reputation: 3838

You could use sed:

$ sed ':a;N;$!ba;s/\n/,/g' test.txt 
a,b,c,d,e,f,g

See this answer to read more details.

Otherwise, for the other solutions, it's very easy to remove the final comma. For example with sed :

$ cat test.txt|tr "\n" ","|sed "s/,$//g" 
a,b,c,d,e,f,g
$ while read line; do printf "%s%s" $line "," ; done < test.txt|sed "s/,$//g" # with your solution
a,b,c,d,e,f,g

Upvotes: 2

Reinstate Monica Please
Reinstate Monica Please

Reputation: 11593

Just use the tr command

> string=$(tr $'\n' ',' < "yourfile.txt"); echo "${string%,*}"
a,b,c,d,e,f,g

With the bash substitution to remove the trailing comma.

Upvotes: 2

chepner
chepner

Reputation: 531165

A "one"-liner taking advantage of the IFS variable and arrays:

str=$( IFS=$'\n'; arr=( $(<test.txt) ); IFS=,; echo "${arr[*]}" )

First, the entire file is read into an array, using a line-feed as the field splitter to ensure one line per element. Next, the field separator is changed to a comma so that the entire array is joined into one comma-delimited string.

Upvotes: 2

Related Questions