Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/macos/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Regex sed没有删除文件中每行开头的所有空白_Regex_Macos_Sed - Fatal编程技术网

Regex sed没有删除文件中每行开头的所有空白

Regex sed没有删除文件中每行开头的所有空白,regex,macos,sed,Regex,Macos,Sed,我有几行代码如下: 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 我能够从每一行的开头抑制前导空格,但不能从第二行抑制前导空格。我不明白为什么塞德在这方面不及格 bash-3.2$ sed 's/^ *//g' remo

我有几行代码如下:

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
我能够从每一行的开头抑制前导空格,但不能从第二行抑制前导空格。我不明白为什么塞德在这方面不及格

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$
使现代化
非常感谢您的帮助。

第二行在前4个空格后有制表符-这就是^I的含义。您只删除空格,而不删除制表符

sed $'s/^[ \t]*//' remove_space.txt
顺便说一句,当模式以^或$锚定时,不需要使用g修饰符。这些模式在一行中只能匹配一次。

第二行中的四个^I是表格,这些是仍然显示在输出中的空白字符

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

sed 's/^[[:space:]]*//' remove_space.txt

这里的问题是因为您的文件在行的开头包含一些\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 
来处理空格和标签。此外,出于可移植性的原因,请使用帮助中定义的POSIX正则表达式


您的命令在GNU sed 4.2.2上正常工作。你在用什么版本的?你能在你的文件里查一下DOS风格的行终止符吗?发布文件remove_space.txt的输出我正在从Mac执行此命令,这可能是原因吗?因为从搜索中我了解到GNU sed和Mac中的sed是不同的。是的,它们是不同的,FreeBSD sed可能需要-e,即sed-e。我尝试了使用-e标志,但结果仍然相同。是否可以使用od-c命令或cat-vTE检查您的空格是否实际是空格?是否有理由在sed search and replace命令之前有$?是的,需要将转义序列转换为制表符。\n您的答案使用[[:空格:]不过更好。谢谢!我不知道$@Allan是的,那是我测试它的地方。你可以在你以前的答案中逃逸+,或者通过-E使用扩展正则表达式模式。无论如何+1!@Allan\+只会对GNU使用,从我所知,它与-posix标志不起作用,我真的怀疑它能提供显著的性能提升。如果我同意的话为了弥补我的懒惰,我将首先测试它是否会:如果一切都可以基于GNU,那么在我看来,世界会更好……无论如何!
sed -E 's/^[[:space:]]+//' remove_space.txt 
 -E        Interpret regular expressions as extended (modern) regular
   expressions rather than basic regular expressions (BRE's).  The
   re_format(7) manual page fully describes both formats.