0

Given a text,

$ cat a.txt
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam at magna sed libero accumsan ultrices. Proin varius tortor risus, at pulvinar quam auctor 
vitae.


Etiam iaculis ipsum quis lacus convallis finibus. Nunc fermentum, nunc sit amet egestas congue, odio quam sollicitudin velit, quis venenatis augue 
nibh sed tortor.

I can't remove that double empty lines using this command.

$ tr '\n\n' '\n' < a.txt 
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam at magna sed libero accumsan ultrices. Proin varius tortor risus, at pulvinar quam auctor 
vitae.


Etiam iaculis ipsum quis lacus convallis finibus. Nunc fermentum, nunc sit amet egestas congue, odio quam sollicitudin velit, quis venenatis augue 
nibh sed tortor.

Replacing single new line with other char works, isn't it strange?

  • Why settle for tr? Couldn't you just use sed or awk? – Quora Feans Jan 5 at 12:11
  • That's due to personal reason: I've read that using sed for multiline is awkward, that --script switch make me allergic ^^. While awk is not my familiar.. (I though tr would be simpler to use) – Abdillah Jan 5 at 23:52
0

tr only looks at one character at a time, so tr ab cd tells to change a->c, and b->d. It doesn't care which order the characters come in, or if any of them are missing, so:

$ echo "a b bba" | tr ab cd
c d ddc

If the second list is shorter, it's extended to the length of the first by repeating the last character. So tr abc d would change any of a, b, c to d, and tr '\n\n' '\n' changes newlines to newlines, which doesn't do anything.

$ echo "a b bcba" | tr abc d
d d dddd

That said, there's the -s option to squeeze identical characters after a replacement, so tr -d '\n' '\n' would replace newlines with newlines and then leave only one newline in a row:

$ cat test.txt
foo


bar

doo
$ cat test.txt  | tr -s '\n' '\n'
foo
bar
doo

Note that in your example, you have two empty lines, so three newlines in a row. If you want to remove newlines so that there's only one empty line (two newlines) left between the paragraphs, then I don't think you can do that with tr. But you could use e.g. awk. With test.txt from above:

$ awk '/./ { e=0 } /^$/ { e += 1 } e <= 1' < test.txt  
foo

bar

doo

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.