tags:

views:

192

answers:

4

I am looking for a way to remove 'stray' carriage returns occurring at the beginning or end of a file. ie:

\r\n <-- remove this guy
some stuff to say \r\n
some more stuff to say \r\n
\r\n <-- remove this guy

How would you match \r\n followed by 'nothing' or preceded by 'nothing'?

A: 

Depending on the language either the following regex in multiline mode:

^\r\n|\r\n$

Or this regex:

\A\r\n|\r\n\z

The first one works in e.g. perl (where ^ and $ match beginning/end of line in single-line mode and beginning/end of string in multiline mode). The latter works in e.g. ruby.

sepp2k
A: 

Here's a sed version that should print out the stripped file:

 sed -i .bak -e '/./,$!d' -e :a -e '/^\n*$/{$d;N;ba' -e '}' foo.txt

The -i tells it to perform the edit in-place and the .bak tells it to back up the original with a .bak extension first. If memory is a concern, you can use '' instead of .bak and no backup will be made. I don't recommend unless absolutely necessary, though.

The first command ('/./,$!d' should get rid of all leading blank lines), and the rest is to handle all trailing blank lines.

See this list of handy sed 1-liners for other interesting things you can chain together.

Hank Gay
A: 

^\s+|\s+$

\s is whitespace (space, \r, \n, tab)
+ is saying 1 or more
$ is saying at the end of the input
^ is saying at the start of the input
amikazmi
He wants to remove only the \r\n
Thiyagaraj
In most implementations $ and ^ refer to the beginning/end of the line, not the whole string, unless you specifically enable multiline mode.
sepp2k
@Thiyagaraj: he said *\r\n followed by 'nothing' or preceded by 'nothing'* so I guessed he meant spaces.@sepp2k: correct
amikazmi
A: 

Try this regular expression:

^(\r\n)+|\r\n(\r\n)+$
Gumbo