Reputation: 2011
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.
Upvotes: 10
Views: 23901
Reputation: 67829
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
Upvotes: 15
Reputation: 42020
Note that in the more general case of applying several filters in a row to an input file without using intermediate files, the solution is to use pipes:
sed -e 's/^[ \t]*//' a | sed -e 's/ *$//' > c
Obviously they are not required here because one invocation of sed is sufficient, but if the second sed command was something different, like uniq or sort, then this pattern is the right one.
Upvotes: 0
Reputation: 42020
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.
Upvotes: 3
Reputation: 342363
easier way, using awk
awk '{$1=$1}1' file
or
awk '{gsub(/^ +| +$/,"")}1' file
Upvotes: 7