-2

I'm writing a bash script which calls vim to modify another file, then join all the lines in the file using '\n'. Code I tried in script:

vi filefff (then I modify the text in filefff)
cat filefff
new=$(cat filefff | sed 'N;N;s/\n/\\n/g')
echo $new

Here is the problem:

for example, if there are two lines in the file: first-line aa, second-line bb,

aa
bb

then I change the file to:

aa
bb
cc
dd
ee

the result of echo $new is aa"\n"bb cc"\n"dd ee"\n".The command only joined some of the lines.

And then I append some more lines:

aa
bb
cc
dd
ee
ff
gg
hh

the result is aa"\n"bb cc"\n"dd ee"\n"ff, the 'hh' is gone.

So I'd like to know why and how to join all the lines with '\n', no matter how many lines I'm going to append to the file.

KamilCuk
  • 96,430
  • 6
  • 33
  • 74
Liu
  • 47
  • 1
  • 6

1 Answers1

0

As enhancement to 'sed' or 'tr' solutions suggested by comments, which can produce VERY long line, consider the following option, which can produce more human-friendly output, allowing a cap on the maximum line length (200 in the examples below)

# Use fold to limit line length
cat filefff | tr '\n' ' ' | fold -w200

# Use fmt to combine lines
cat filefff | fmt -w200

# Use xargs to format
cat filefff | xargs -s200

Note that the 'fmt' will assume line breaks are required when an empty line is provided.

dash-o
  • 12,431
  • 1
  • 6
  • 32