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,
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:If the output should have a trailing newline (thanks, Ed Morton):
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 firstprint
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 thatprint
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 firsts
command working.)Well you can use labels:
You can also use paste command: