对 linux 中的脚本编写相当新,所以我希望这很简单。如果该目录包含一个包含特定文本的文件,我需要将包含多个文件的目录移动到另一个位置。
我有一个命令,它给我一个符合我的条件的目录列表:
find . -name 'file.name' -print0 | xargs -0 grep -l "foo" | sed 's#\(.*\)/.*#\1#' | sort -u
现在我只需要获取结果并将它们与可执行脚本中的 mv 命令结合起来。
您可以使用xargs
with replacement 来获得所需的效果:
commands to get directory list | xargs -i mv "{}" <destination>
假设您发布的管道中的所有内容都是目录名称:
$target=/home/me/example
find . -name 'file.name' -print0 |
xargs -0 grep -l "foo" |
sed 's#\(.*\)/.*#\1#' |
while read line #line is a variable with the contents of one line
do
mv $line $target
done
哦,去掉 sort -u 不需要它移动目录,它会“序列化”你的管道,在查找完成之前你不能排序,所以移动不会开始,没有它,移动可以开始很快找到第一个项目。
反引号操作符计算一个命令并将其放置在命令行中,stdout
就像您在命令行中输入它一样。所以,在你的情况下:
mv `find . -name 'file.name' -print0 | xargs -0 grep -l "foo" | sed 's#\(.*\)/.*#\1#'` target