UNIX sed命令不删除cat输出中的空格

时间:2014-03-05 16:54:55

标签: linux shell unix sed awk

我有一个文件如下。

Hi this is first line
    this is second line
    this is third line

预期是:

Hi this is first line
this is second line
this is third line

我使用的是

cat file.txt | sed 's/ //g'

返回,

Hi this is first line
    this is second line
    this is third line

5 个答案:

答案 0 :(得分:3)

对于便携式sed命令,请使用:

sed 's/^[[:blank:]]*//' file

[[:blank:]]匹配空格或标签。

编辑:使用awk删除所有空格:

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

或sed:

sed 's/[[:blank:]]*//g' file

答案 1 :(得分:1)

 cat file.txt | sed -e 's/^[ \t]*//'

OR

 sed 's/^[ \t]*//' file.txt 

如果要修改file.txt并删除行开头的空格:

sed -i 's/^[ \t]*//' file.txt

答案 2 :(得分:1)

示例中的

sed将替换所有空格

sed 's/^[ \t]*//' file.txt

答案 3 :(得分:1)

试试这一行

sed -r 's/^\s*//' file

删除所有空格(标签):sed -r 's/\s//g' file

kent$ echo "Hi this is first line
    this is second line
    this is third line"|sed -r 's/\s//g' 
Hithisisfirstline
thisissecondline
thisisthirdline

答案 4 :(得分:1)

从输入中删除所有空格的最有效方法可能根本不使用sed,但

tr -d '[:blank:]' < file.txt

这与您最初要求的不同(仅删除初始空格)。