How do I convert a file with newline delimited content into a single line like below?
blah
blah
into
blah\nblah
Or sed:
sed -e ':a' -e 'N' -e '$!ba' -e 's/\n/\n/g'
(credits to @kenorb from other question How can I replace a newline (\n) using sed?)
Multiple choices with output piped to sed:
awk:
awk 1 ORS='\\n' file | sed 's/..$//'
Perl:
perl -p -e 's/\n/\\n/' file | sed 's/..$//'
sed
There is also a way to do it in just in sed as was mentioned in other post. However, this:
sed ":a;N;$!ba;s/\n/\\n/g" file
May not work as $!ba
might be expanded in some systems to the last shell command starting with ba
. I would suggest other solution:
sed ':a;{N;s/\n/\\n/};ba' file
UPDATE:
I noticed that the only tag is the bash so if you want to use only the shell command:
IFS=$'\n'
last=$(<file wc -l)
cnt=0
while IFS= read -r line ; do
cnt=$[$cnt +1]
if [ $cnt -eq $last ]
then
printf "%s" "$line"
else
printf "%s" "$line\\n"
fi
done < file