sed不会从文件中每一行的开头删除所有空格

时间:2019-02-06 09:01:49

标签: 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

我能够从每行的开始而不是从第二行开始抑制前导空格。我不明白为什么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$

任何帮助,我们将不胜感激。

3 个答案:

答案 0 :(得分:2)

第二行在前4个空格后有TAB字符-这就是class BookingRequestSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = BookingRequest fields = ( 'last_name', 'email', 'startdate', 'enddate', 'guests', 'building' ) def create(self, validated_data): bookingrequest_obj = super().create(validated_data) if 'message' in self.context: BookingRequestMessage( bookingrequest=bookingrequest_obj, message=self.context['request'].data.get('message'), sender=BookingRequestMessage.Mieter ).save() return bookingrequest_obj 所表示的含义。您只删除空格,而不是TAB。

^I

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

答案 1 :(得分:2)

第二行中的四个^I是制表符,它们是仍显示在输出中的空格字符。

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

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

答案 2 :(得分:2)

这里的问题是因为您的文件在行首包含了\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 

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

 -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.