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:
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
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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.