且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

了解管道和重定向命令

更新时间:2022-12-09 13:52:08

我会支持你已经证明了三种方法打破这


  • > 将重定向从所有输出找到到一个名为 RM 文件code>(将无法工作,因为你只是附加到文件)。

  • | 将从输出管道找到 RM 命令(不会起作用,因为 RM 不上阅读标准输入

  • -exec RM -rf {} \\; 将运行 RM -rf ,在每个项目( {} )的找到认定(将工作,因为它把文件作为参数传递给 RM )。

您将需要使用 -exec 标志或者管道进入的xargs 命令(男人xargs的),而不是 | > ,以达到所期望的行为

编辑:为@dmckee说,你也可以使用 $()运营商串插,即:室射频$(找到。-name* .SWP)(如果你有大量的文件,由于参数长度的限制,这将失败)。

I want to understand the real power of pipe and redirection command.As per my understanding,| takes the output of one command result as the input of itself. And, > is helps in output redirecting .If it is so,

find . -name "*.swp" | rm 
find . -name "*.swp" > rm 

why this command is not working as expected .For me above command means

  1. Find the all files recursively whose extension is .swp in current directory .
  2. take the output of 1. and remove all whose resulted files .

FYI,yes i know how to accomplish this task . it can be done by passing -exec flag .

find . -name "*.swp"-exec rm -rf {} \;

But as I already mentioned,i want to accomplish it with > or | command.
If i was wrong and going in wrong direction,please correct me and explain redirection and pipe command. Where we use whose commands ? please dont mention simple book examples i read all whose thing . try to explain me some complicated thing .

I'll break this down by the three methods you have shown:

  • > will redirect all output from find into a file named rm (will not work, because you're just appending to a file).
  • | will pipe output from find into the rm command (will not work, because rm does not read on stdin)
  • -exec rm -rf {} \; will run rm -rf on each item ({}) that find finds (will work, because it passes the files as argument to rm).

You will want to use -exec flag, or pipe into the xargs command (man xargs), not | or > in order to achieve the desired behavior.

EDIT: as @dmckee said, you can also use the $() operator for string interpolation, ie: rm -rf $(find . -name "*.swp") (this will fail if you have a large number of files, due to argument length limits).