使用 sed 从文件列表中删除字符串失败

使用 sed 从文件列表中删除字符串失败

我使用的是 bash (Mac OS X)。我有一个文件列表,其中有一个我想删除的字符串:

$ grep -l \</html\> *.html  
21888601.html  
21906283.html  
21977081.html  
...

所有匹配的文件都以此格式命名 (.html)。然后我试试这个:

$ grep -l \</html\> 27776977.html | xargs -0 sed -i.back '/<\/html>/d'

shell 只是打印出从 grep 返回的文件列表和一个错误:

sed: 21888601.html  
21906283.html  
21977081.html  
...
: File name too long

这些文件名显然不是太长,所以这里还有一些其他错误。另外,当我在具有字母名称(并非所有数字)的文件上测试此功能时,我没有收到错误。

我也尝试过:

$ grep -l \</html\> 27776977.html | xargs -0 sed -i.back '/<\/html>/d'
sed: 27776977.html
: No such file or directory

$ grep -l \</html\> 27776977.html
27776977.html

sed 无法处理数字文件名吗?或者这里还有其他问题吗?

答案1

因为您使用该-0选项,xargs将查找空字符,而不是空格来终止输入文件名。这会导致找到的所有文件grep连接到一个长字符串而不是单独的文件。

更多详情来自man xargs

-0, --null
              Input items are terminated by a null character instead of by whitespace,  and  the  quotes  and
              backslash  are  not  special  (every  character  is taken literally).  Disables the end of file
              string, which is treated like any other argument.  Useful when input items might contain  white
              space,  quote  marks,  or backslashes.  The GNU find -print0 option produces input suitable for
              this mode.

在这种情况下,您的文件名没有任何特殊字符,因此您应该删除该-0选项。

答案2

如果您使用with ,则需要-Z选项 in 。grep-0xargs

您可以看到错误file name to long列出了所有连接在一起的文件名。

man grep:

-Z, --null
          Output  a  zero  byte (the ASCII NUL character) instead of the character that normally follows a file name.
          For example, grep -lZ outputs a zero byte after each file name instead of the usual newline.   This  option
          makes  the  output  unambiguous,  even  in  the  presence  of file names containing unusual characters like
          newlines.  This option can be used with commands like find -print0, perl -0,  sort  -z,  and  xargs  -0  to
          process arbitrary file names, even those that contain newline characters.

通常grep,xargs和其他命令使用换行符或空格作为分隔符。但可以要求他们使用 null,这在数据有空格时很有用。

xargs使用选项-0告诉它它的输入是空分隔的,grep使用-Z--null告诉它创建空分隔的输出。

如果您grep不支持,则从中-Z删除。如果文件名中没有换行符,这应该可以工作。-0xargs

相关内容