[英]Execute multiple commands on target files from find command
Let's say I have a bunch of *.tar.gz
files located in a hierarchy of folders. 假设我在文件夹层次结构中有一堆
*.tar.gz
文件。 What would be a good way to find those files, and then execute multiple commands on it. 找到这些文件,然后在其上执行多个命令的好方法。
I know if I just need to execute one command on the target file, I can use something like this: 我知道是否只需要在目标文件上执行一个命令,就可以使用以下命令:
$ find . -name "*.tar.gz" -exec tar xvzf {} \;
But what if I need to execute multiple commands on the target file? 但是,如果我需要在目标文件上执行多个命令怎么办? Must I write a bash script here, or is there any simpler way?
我必须在这里写一个bash脚本,还是有更简单的方法?
Samples of commands that need to be executed a A.tar.gz
file: 需要在
A.tar.gz
文件中执行的命令示例:
$ tar xvzf A.tar.gz # assume it untars to folder logs
$ mv logs logs_A
$ rm A.tar.gz
Writing a shell script is probably easiest. 编写Shell脚本可能是最简单的。 Take a look at sh for loops .
看一下sh的循环 。 You could use the output of a find command in an array , and then loop over that array to perform a set of commands on each element.
您可以在数组中使用find命令的输出 ,然后在该数组上循环以对每个元素执行一组命令。
For example, 例如,
arr=( $(find . -name "*.tar.gz" -print0) )
for i in "${arr[@]}"; do
# $i now holds each of the filenames output by find
tar xvzf $i
mv $i $i.suffix
rm $i
# etc., etc.
done
Here's what works for me (thanks to Etan Reisner suggestions) 这是对我有用的(感谢Etan Reisner的建议)
#!/bin/bash # the target folder (to search for tar.gz files) is parsed from command line
find $1 -name "*.tar.gz" -print0 | while IFS= read -r -d '' file; do # this does the magic of getting each tar.gz file and assign to shell variable `file`
echo $file # then we can do everything with the `file` variable
tar xvzf $file
# mv untar_folder $file.suffix # untar_folder is the name of folder after untar
rm $file
done
As suggested, the array way is unsafe if file name contained space(s), and also doesn't seem to work properly in this case. 如建议的那样,如果文件名包含空格, 则数组方法是不安全的,并且在这种情况下似乎也无法正常工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.