Skip to main content

Removing (some) newlines

I wanted to consolidate certain lines in a file:

$ cat file.txt
aaa013
 - foo (11)
    - bar 11

aaa015
 - foo (15)
    - bar 15
The strings "aaa", "foo" and "bar" were kinda static, but not the numbers. I wanted something like this instead:
aaa013 - foo (11)    - bar 11
aaa015 - foo (15)    - bar 15
Sure, I can use tr(1) to remove all newlines:
$ tr -d '\n' < file.txt
aaa013 - foo (11)    - bar 11aaa015 - foo (15)    - bar 15
...but that's not exactly what I wanted. The following trick did help though:
$ sed 's/^aaa.*/&:/;s/foo.*/&:/' file.txt | perl -p -e "s/:\n//"
aaa013: - foo (11):    - bar 11

aaa015: - foo (15):    - bar 15
Since some strings were somewhat static, I added a colon (":") to the end of those strings. That way the Perl snippet had something to look for when replacing newlines ("\n", with a preceding colon) with nothing.