文件1:
hello
world
如何在不使用中间文件的情况下使用sed删除此文件中的前导/尾随空格 - 使用一个命令?
当前我有的是:
sed -e 's/^[ \t]*//' a > b
对于前导空格。
sed 's/ *$//' b > c
这是用于尾随空格的。
文件1:
hello
world
sed -e 's/^[ \t]*//' a > b
对于前导空格。
sed 's/ *$//' b > c
这是用于尾随空格的。
你差不多理解了:
sed -e 's/^[ \t]*//;s/[ \t]*$//' a > c
sed
版本中,还有一种内联编辑的选项:sed -i -e 's/^[ \t]*//;s/[ \t]*$//' a
\s
,它是通用的“所有空格字符”。 - Matthew Scharleysed -e 's/^[ \t]*//;s/[ \t]*$//' a > c
吗? - Nikos Alexandrissed -e 's/^[ \t]*//;s/[ \t]*$/' a > c
对我无效(bash 版本 4.3.30,Funtoo-Linux)。 - Nikos Alexandrisawk '{$1=$1}1' file
awk '{gsub(/^ +| +$/,"")}1' file
awk
是一个很棒的工具。 - mouvicielperl -lape 's/^\s+|\s+$//g'
说实话,我最擅长perl正则表达式,所以我发现perl -lape
比sed -e
更容易使用。
另外,要回答原始问题,您可以像这样让sed执行多个操作:
sed -e 's/something/something else/' -e 's/another substitution/another replacement/'
sed -e 's/^[ \t]*//' a | sed -e 's/ *$//' > c
显然在这里它们不是必需的,因为一次调用sed就足够了,但如果第二个sed命令是不同的,比如uniq或sort,那么这个模式就是正确的。