I'm using sed
to replace my file of new lines \n
with ','
which works fine however, in my last item, I don't want the ,
.
How can I remove this?
Example:
sed 's/\n/,/g' myfile.out > myfile.csv
Output:
1,2,3,4,5,6,
I'm using sed
to replace my file of new lines \n
with ','
which works fine however, in my last item, I don't want the ,
.
How can I remove this?
Example:
sed 's/\n/,/g' myfile.out > myfile.csv
Output:
1,2,3,4,5,6,
Well you can use labels:
$ cat file
1
2
3
4
5
6
$ sed ':a;N;s/\n/,/;ba' file
1,2,3,4,5,6
You can also use paste command:
$ paste -sd, file
1,2,3,4,5,6
Consider jaypal singh's paste
solution, which is the most efficient and elegant.
An awk
alternative, which doesn't require reading the entire file into memory first:
awk '{ printf "%s%s", sep, $0; sep = "," }' myfile.out > myfile.csv
If the output should have a trailing newline (thanks, Ed Morton):
awk '{ printf "%s%s", sep, $0; sep = "," } END { printf "\n" }' myfile.out > myfile.csv
For the first input line, sep
, due to being an uninitialized variable, defaults to the empty string, effectively printing just $0
, the input line.
Setting sep
to ","
after the first print
ensures that all remaining lines have a ,
prepended.
END { printf "\n" }
prints a trailing newline after all input lines have been processed. (print ""
would work too, given that print
appends the output record separator (ORS
), which defaults to a newline).
The net effect is that ,
is only placed between input lines, so the output won't have a trailing comma.
You could add a second s
command after the first: sed -z 's/\n/,/g ; s/,$//
. This removes a comma at the end. (The option -z
is from gnu sed and I needed it to get the first s
command working.)