tags:

views:

99

answers:

3

What is the simplest way to parse line continuation characters? This seems like such a basic action that I'm surprised there's no basic command for doing this. 'while read' and 'while read -r' loops don't do what I want, and the easiest solution I've found is the sed solution below. Is there a way to do this with something basic like tr?

$ cat input
Output should be \
one line with a '\' character.
$ while read l; do echo $l; done < input
Output should be one line with a '' character.
$ while read -r l; do echo $l; done < input
Output should be \
one line with a '\' character.
$ sed '/\\$/{N; s/\\\n//;}' input
Output should be one line with a '\' character.
$ perl -0777 -pe 's/\\\n//s' input
Output should be one line with a '\' character.

A: 

The regex way looks like the way to go.

Robert Fraser
A: 

I would go with the Perl solution simply because it will likely be the most extensible if you want to add more functionality later.

Imagist
+1  A: 

If by "simplest" you mean concise and legible, I'd suggest your perl-ism with one small modification:

$ perl -pe 's/\\\n//' /tmp/line-cont

No need for the possibly memory intensive ... -0777 ... (whole file slurp mode) switch.

If, however, by "simplest" you mean not the leaving shell, this will suffice:

$ { while read -r LINE; do
    printf "%s" "${LINE%\\}";    # strip line-continuation, if any
    test "${LINE##*\\}" && echo; # emit newline for non-continued lines
    done; } < /tmp/input

(I prefer printf "%s" $USER_INPUT to echo $USER_INPUT because echo cannot portably be told to stop looking for switches, and printf is commonly a built-in anyway.)

Just tuck that in a user-defined function and never be revolted by it again. Caution: this latter approach will add a trailing newline to a file which lacks one.

pilcrow