我有几行代码如下:
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
在那里失败了。
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$
更新
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$
任何帮助都非常感谢。
发布于 2019-02-06 09:19:44
这里的问题是,您的文件在行的开头包含了一些\t
,如cat -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 $
您可以将命令更改为:
sed -E 's/^[[:space:]]+//' remove_space.txt
来照顾spaces
和tabs
。另外,出于可移植性的原因,请使用POSIX
正则表达式,如帮助https://www.freebsd.org/cgi/man.cgi?query=sed&sektion=&n=1中所定义的那样。
-E将正则表达式解释为扩展(现代)正则表达式,而不是基本正则表达式(BRE)。re_format(7)手册页面完全描述了这两种格式。
发布于 2019-02-06 09:18:17
第二行在前4个空格之后有TAB字符--这就是^I
的含义。你只是在移除空间而不是TAB。
sed $'s/^[ \t]*//' remove_space.txt
顺便说一句,当一个模式被^
或$
锚定时,没有必要使用^
修饰符。这些模式只能在一行上匹配一次。
发布于 2019-02-06 09:19:08
第二行中的四个^I
是表格,它们是仍然出现在输出中的空白字符。
我建议您使用以下命令从行的开头删除任何类型的空格:
sed 's/^[[:space:]]*//' remove_space.txt
https://stackoverflow.com/questions/54549861
复制相似问题