Linux的我为什么不能管找到结果RM? [英] Linux why can't I pipe find result to rm?

查看:139
本文介绍了Linux的我为什么不能管找到结果RM?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对不起,如果这是一个noobie问题,但我不能找到一个很好的答案。

sorry if this is a noobie question but I can't find a good answer.

要找到然后取出东西,我可以使用

To find then remove something I can use

find . -name ".txt" -exec rm "{}" \;

但为什么我就不能管的结果,RM像

But why can't I just pipe the results to rm like

find . -name ".txt" | rm 

就像我觉得应该是到grep

like I would pipe it to grep

find . -name ".txt" | grep a

我从某处,RM阅读并不需要从标准输入,因此,我不能管,但到底是什么意思呢?当我在RM型A.TXT它从标准输入读取就像我可以grep吧?或者是有标准输入和命令行之间的差异。救命啊!

I've read from somewhere that rm doesn't take input from stdin and therefore I can't pipe it but what does that mean? When I type in rm a.txt it reads from standard input just like I can grep right? Or is there a difference between stdin and command line. Help!

推荐答案

要扩大@Alex Gitelman的回答:是的,有标准输入和命令​​行之间的差异

To expand on @Alex Gitelman's answer: yes, there's a difference between "standard input" and the command line.

当你键入 RM A.TXT b.txt c.txt ,你以后 RM 列出文件被称为的参数的,并提供通过一个特殊的变量RM(名为的argv 内部)。标准输入,而另一方面,看上去到Unix程序就像一个名为标准输入文件。程序可以从该文件中读取数据,就像它,如果它打开磁盘上的常规文件,并且从读取。

When you type rm a.txt b.txt c.txt, the files you list after rm are known as arguments and are made available to rm through a special variable (called argv internally). The standard input, on the other hand, looks to a Unix program like a file named stdin. A program can read data from this "file" just as it would if it opened a regular file on disk and read from that.

RM ,像许多其他程序,需要在命令行及其参数,但忽略标准输入。你可以管任何事情它你喜欢的;它会只是把这些数据了。这就是的xargs 就派上用场了。它读取标准输入线,把他们变成命令行参数,这样可以有效地管数据到另一个程序的命令行。这是一个巧妙的方法。

rm, like many other programs, takes its arguments from the command line but ignores standard input. You can pipe anything to it you like; it'll just throw that data away. That's where xargs comes in handy. It reads lines on standard input and turns them into command-line arguments, so you can effectively pipe data to the command line of another program. It's a neat trick.

例如:

find . -name ".txt" | xargs rm
find . -name ".txt" | grep "foo" | xargs rm  

请注意,这将无法正常工作,如果有包含换行符或空格的任何文件名。
为了处理包含换行符或空格,你应该使用的文件名:

Note that this will work incorrectly if there are any filenames containing newlines or spaces. To deal with filenames containing newlines or spaces you should use instead:

find . -name ".txt" -print0 | xargs -0 rm

这将告诉找到以空字符,而不是一个新行终止的结果。
然而,的grep 不会像以前那样工作,然后。相反,使用:

This will tell find to terminate the results with a null character instead of a newline. However, grep won't work as before then. Instead use this:

find . -name ".txt" | grep "foo" | tr "\n" "\0" | xargs -0 rm

这个时间 TR 用于所有的换行转换成空字符。

This time tr is used to convert all newlines into null characters.

这篇关于Linux的我为什么不能管找到结果RM?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆