views:

438

answers:

3

File1:

  hello  
  world

How would one delete the leading/trailing blank spaces within this file using sed - using one command (no intermediate files)?

I've currently got:

sed -e 's/^[ \t]*//' a > b

For leading spaces.

sed 's/ *$//' b > c

And this for trailing spaces.

+4  A: 

You almost got it:

sed -e 's/^[ \t]*//;s/[ \t]*$/' a > c

Moreover on some flavours of sed, there is also an option for editing inline:

sed -i -e 's/^[ \t]*//;s/[ \t]*$/' a
mouviciel
I'd also consider matching `\s` which is the generic 'all whitespace characters'.
Matthew Scharley
+3  A: 

easier way, using awk

awk '{$1=$1}1' file

or

awk '{gsub(/^ +|  +$/,"")}1' file
ghostdog74
The first one worked perfectly and is the most simplistic - I know its not what I asked (i.e. sed) - but its so elegant :). I'll look into awk now.
The first one removes all spurious whitespaces, not only leading and trailing. The second one works best. `awk` is a great tool.
mouviciel
Ah, I see the other spaces removed with the first one now - the second one works without extra deletions.
A: 
perl -lape 's/^\s+|\s+$//g'

Honestly, I know perl regexps the best, so I find perl -lape much easier to use than sed -e.

Also, to answer the original question, you can have sed execute multiple operations like this:

sed -e 's/something/something else/' -e 's/another substitution/another replacement/'

Apparently you can also put the two substitutions in one string and separate them with a semicolon, as indicated in another answer.

Ryan Thompson