find, xargs 遇到 特殊字符

xargs的基本使用也不必多言,这里主要讲一下我使用过程中遇到的问题:

问题出在用find找出的文件传给xargs处理时,却出现了问题。我简化了一下问题,如下:

]$ touch "a b"
[lyu@swe-vm-kcr-pr01 ~]$ find . -maxdepth 1 -name "a*b" | xargs rm
rm: cannot remove `./a': No such file or directory
rm: cannot remove `b': No such file or directory

虽然文件名包含空格也是蛮奇葩的,但是世界上就是有各种各样奇葩的存在。这时候就等于rm a b,自然就报错了。

那遇到这种问题该如何处理呢? 答案就是xargs的 -0选项。

--null, -0
              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将会使用null来分割参数而不是空格,当然find的输入也需要使用null来分隔,否则还是会出错:

$ find . -maxdepth 1 -name "a*b" | xargs -0 rm
rm: cannot remove `./a b\n': No such file or directory

而find也提供 -print0功能。

$ find . -maxdepth 1 -name "a*b" -print0 | xargs -0 rm

其实xargs还有很多功能,像-L -I选项,不过我还是用的很少,不过了解一下是最好的,等到用的时候能想到,再去细看不迟。

转载于:https://my.oschina.net/maxio/blog/519352

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值