-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
  • 120,984
  • 8
  • 59
  • 111
Liu
  • 67
  • 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
  • 13,723
  • 1
  • 10
  • 37
  • `sed '\n' ' '` -> `tr` ;) – KamilCuk Nov 23 '19 at 20:15
  • @KamilCuk Thanks for feedback! corrected. – dash-o Nov 23 '19 at 21:26
  • `cat filefff | tr '\n' ' '` = `tr '\n' ' ' < filefff` – Ed Morton Nov 24 '19 at 23:12
  • @EdMorton You are correct - using '<' is more efficient and clear in this case. I usually prefer to post answers that follow the question style. I believe it will help the OP integrate the answer (or ideas from the answer) into his own problem. This is true for many MRE, when the OP simplified the real problem. In reality, the `cat` may be a big pipeline. – dash-o Nov 25 '19 at 05:37
  • I usually agree but in this case the OP shows that they `vi` the file before `cat`-ing it so - it's a file. – Ed Morton Nov 25 '19 at 14:30