找回密码
 注册

QQ登录

只需一步,快速开始

查看: 172|回复: 1

linux: find files towards further command process

[复制链接]
发表于 2013-12-12 13:58:05 | 显示全部楼层 |阅读模式
  1. find . -name myFile -exec cp /home/myuser/myFile {} ';'
复制代码

A breakdown / explanation of this:
  • find: invoking the find command
  • .: start search from current working directory.
  • Since no depth flags are specified, this will search recursively for all subfolders
  • -name myFile: find files with the explicit name myFile
  • -exec: for the search results, perform additional commands with them
  • cp /home/myuser/myFile {}: copies /home/myuser/myFile to overwrite each result returned by find to ; think of {} as where each search result goes.
  • ';': used to separate different commands to be run after find

copy the one file /home/myuser/myFile to overwrite any myFile's found by find in the cmd

 楼主| 发表于 2013-12-12 14:06:05 | 显示全部楼层
If none of the filenames have spaces or special characters (they consist only of letters, numbers, dashes, and underscores), then the following is a simple solution that will work. You can use $(command) to execute a command, and substitute the results into the arguments of another command. The shell will split the result on spaces, tabs, or newlines, and for assign each value to $f in turn, and run the command on each value.
  1. for f in $(find . -name myFile)
  2. do
  3.     cp something $f
  4. done
复制代码

If you do have spaces or tabs, you could use find's -exec option. You pass -exec command args, putting {} where you want the filename to be substituted, and ending the arguments with a ;. You need to quote the {} and ; so that the shell doesn't interpret them.
  1. find . -name myFile -exec cp something "{}" \;
复制代码

Sometimes -exec is not sufficient. For example, in this question, they wanted to use Bash parameter expansion to compute the filename. In order to do that, you need to pass -exec bash -c 'your command', but then you will run into quoting problems with the {} substitution. To solve this, you can use -print0 from find to print the results delimited with null characters (which are invalid in filenames), and pipe it to a while read loop that splits parameters on nulls:
  1. find . -name myFile -print0 | (while read -d

  2. \0' f; do
  3.     cp something "$f"
  4.   done)
复制代码


您需要登录后才可以回帖 登录 | 注册

本版积分规则

手机版|小黑屋|BC Morning Website ( Best Deal Inc. 001 )

GMT-8, 2026-4-10 17:47 , Processed in 0.030893 second(s), 15 queries .

Supported by Weloment Group X3.5

© 2008-2026 Best Deal Online

快速回复 返回顶部 返回列表