简体   繁体   English

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

[英]UNIX sed command not removing spaces in cat output

I have a file as below. 我有一个如下文件。

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

Expected is: 预期为:

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

What i used is 我用的是

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

returns, 返回,

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

For a portable sed command use this: 对于便携式sed命令,请使用以下命令:

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

[[:blank:]] matches space or tab. [[:blank:]]匹配空格或制表符。

EDIT: To remove all spaces using awk: 编辑:使用awk删除所有空格:

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

OR sed: 或sed:

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

OR 要么

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

OR if you want to modify file.txt and remove the white spaces in the beginning of the line : 或者,如果您要修改file.txt并删除该行开头的空白:

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

您的示例中的sed将替换所有空格

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

try this line 试试这条线

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

to remove all spaces(tabs): sed -r 's/\\s//g' 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

The most efficient way to remove all blanks from your input is probably not using sed at all, but 从输入中删除所有空格的最有效方法可能根本不是使用sed ,而是

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

That's different from what you have originally asked for, though (removing initial whitespace only). 不过,这与您最初的要求不同(仅删除了初始空白)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM