Trimming Whitespace From Beginning and end of Text Lines

Giorgos Keramidas keramida at ceid.upatras.gr
Fri May 12 08:04:29 PDT 2006


On 2006-05-12 09:50, Martin McCormick <martin at dc.cis.okstate.edu> wrote:
> 	This looks like something sed should be able to do, but I
> haven't had any luck at all.  I wanted to remove any whitespace
> that has accidentally gotten added to the beginning or end of
> some lines of text.  I made a test file that looks like:
>
> left justified.
> 	                                       lots of spaces.
>
> and the best I have done so far is to get rid of about 3 spaces.
>
> Attempt 1.
>
> #! /usr/bin/sed -f
> s/ \+//g
> s/^ //g
> s/ $//g

This fails to remove TAB characters from either the start or the
end of a line.

> 	This looks like it should do the job, but the leading and
> trailing spaces are still mostly there.
>
> 	I wrote another script.  Attempt 2.
>
> #! /bin/sh
>
> sed 's/^[[:space:]]//g' \
> |sed 's/[[:space:]]$//g'

This fails to remove multiple occurences of the [[:space:]] class.

There are at least the following ways:

	sed -i -e 's/^[[:space:]]*' -e 's/[[:space:]]*$//' file ...
	perl -pi -e 's/^\s*(\S.*\S)[ \t]*$/$1/' file ...

The first one seems more straightforward to me most of the time,
but there are times I find Perl's `-pi -e ...' idiom very convenient.



More information about the freebsd-questions mailing list