首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >sed没有从文件中每一行的开头删除所有空白空间

sed没有从文件中每一行的开头删除所有空白空间
EN

Stack Overflow用户
提问于 2019-02-06 09:01:48
回答 3查看 268关注 0票数 0

我有几行代码如下:

代码语言:javascript
运行
复制
bash-3.2$ cat remove_space.txt
    this is firs line with 2-3 spaces
                    2nd line with more space, this is where the issue is.
          3rd line

我能够从每一行开始压制领先的白空间,但不能从第二行。我不明白为什么sed在那里失败了。

代码语言:javascript
运行
复制
bash-3.2$ sed 's/^ *//g' remove_space.txt
this is firs line with 2-3 spaces
                2nd line with more space, this is where the issue is.
3rd line


bash-3.2$

更新

代码语言:javascript
运行
复制
with `-vte` 

bash-3.2$ cat -vte remove_space.txt
    this is firs line with 2-3 spaces$
    ^I^I^I^I2nd line with more space, this is where the issue is.$
          3rd line $
$
$
bash-3.2$

任何帮助都非常感谢。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2019-02-06 09:19:44

这里的问题是,您的文件在行的开头包含了一些\t,如cat -vTE所示(正如我的注释中所要求的)

代码语言:javascript
运行
复制
bash-3.2$ cat -vte remove_space.txt
    this is firs line with 2-3 spaces$
    ^I^I^I^I2nd line with more space, this is where the issue is.$
          3rd line $

您可以将命令更改为:

代码语言:javascript
运行
复制
sed -E 's/^[[:space:]]+//' remove_space.txt 

来照顾spacestabs。另外,出于可移植性的原因,请使用POSIX正则表达式,如帮助https://www.freebsd.org/cgi/man.cgi?query=sed&sektion=&n=1中所定义的那样。

-E将正则表达式解释为扩展(现代)正则表达式,而不是基本正则表达式(BRE)。re_format(7)手册页面完全描述了这两种格式。

票数 2
EN

Stack Overflow用户

发布于 2019-02-06 09:18:17

第二行在前4个空格之后有TAB字符--这就是^I的含义。你只是在移除空间而不是TAB。

代码语言:javascript
运行
复制
sed $'s/^[ \t]*//' remove_space.txt

顺便说一句,当一个模式被^$锚定时,没有必要使用^修饰符。这些模式只能在一行上匹配一次。

票数 2
EN

Stack Overflow用户

发布于 2019-02-06 09:19:08

第二行中的四个^I是表格,它们是仍然出现在输出中的空白字符。

我建议您使用以下命令从行的开头删除任何类型的空格:

代码语言:javascript
运行
复制
sed 's/^[[:space:]]*//' remove_space.txt
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54549861

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档