4

How do I convert a file with newline delimited content into a single line like below?

blah
blah

into

blah\nblah
codefx
  • 9,872
  • 16
  • 53
  • 81

2 Answers2

0

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?)

Community
  • 1
  • 1
Nicolae Dascalu
  • 3,425
  • 2
  • 19
  • 17
-1

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
Dave Grabowski
  • 1,619
  • 10
  • 19