如何将包含特定编号的目录中的文件移动到不同的目录中?
How do I move a file from a directory containing a specific number into a different directory?
我想将所有文件从编号为 1995、1996 和 1997 的文件夹移动到不同的文件夹。
我在此列表中发现的大部分内容都与移动包含任何模式的任何文件有关。我希望命令在目录中查找,扫描 .txt 文件的内容,一旦找到 1996,就将其放入 1996 目录。
这意味着如果该命令在目录中查找,扫描 .txt 文件,并在第一行找到 1996 并在第十行找到 1995,它不会将文件同时放入 1996 和 1995文件夹。我希望它只将文件放在 1996 文件夹中。
grep -rl --null --include '*.txt' 1996 . | xargs -0 sh -c 'cp "$@" /folderpath' sh
这似乎是将 1995 文件放入 1996 文件夹,因为它在文件的某处包含 1995。
我认为这样的方法可行:
find . -name '*.txt' -print0 |
xargs -0 -n1 sh -c '
if a=$(head -n1 "" | grep -o "199[567]"); then
mv "" "./$a"
fi
' --
或者,xargs
可以用 while IFS= read -r file; do
循环代替。看起来像:
find . -name '*.txt' -print0 |
while IFS= read -r file; do
if a=$(head -n1 "$file" | grep -o "199[567]"); then
mv "$file" "./$a"
fi
done
find
找到一切
.
- 在当前目录
-name '*.txt'
- 名称以 .txt
结尾
-print0
- 并将它们打印为零终止列表
|
- 管道,将一个命令的输出传递给另一个
while
- 执行一个 do ... done
主体直到命令 returns 非零退出状态
IFS= read -r file
- 阅读零分隔列表的流行助记符,请参阅 bashfaq How can I read a file (data stream, variable) line-by-line (and/or field-by-field)?
head -n1 "$file"
- 从文件中提取第一行
grep
-o
- 只输出匹配的字符串
199[567]
- 匹配 1995
或 1996
或 1997
grep
如果匹配成功则输出零退出状态(在 if
很重要)
a=$(...)
- 将命令的输出分配给 a
。进程替换的退出状态$(...)
是最后执行的命令,在本例中为grep
。
if command
- 仅当命令 return 具有非零退出状态时才执行 then ... fi
主体。 IE。此处仅当 grep 成功匹配字符串时,它才会 return 零退出状态。
mv "$file" "./$a"
- 变量 a
(命名错误...)包含 grep
匹配的字符串,因此它将是 1995
或 1996
或`1997。所以将文件移动到适当的文件夹。
我想将所有文件从编号为 1995、1996 和 1997 的文件夹移动到不同的文件夹。
我在此列表中发现的大部分内容都与移动包含任何模式的任何文件有关。我希望命令在目录中查找,扫描 .txt 文件的内容,一旦找到 1996,就将其放入 1996 目录。
这意味着如果该命令在目录中查找,扫描 .txt 文件,并在第一行找到 1996 并在第十行找到 1995,它不会将文件同时放入 1996 和 1995文件夹。我希望它只将文件放在 1996 文件夹中。
grep -rl --null --include '*.txt' 1996 . | xargs -0 sh -c 'cp "$@" /folderpath' sh
这似乎是将 1995 文件放入 1996 文件夹,因为它在文件的某处包含 1995。
我认为这样的方法可行:
find . -name '*.txt' -print0 |
xargs -0 -n1 sh -c '
if a=$(head -n1 "" | grep -o "199[567]"); then
mv "" "./$a"
fi
' --
或者,xargs
可以用 while IFS= read -r file; do
循环代替。看起来像:
find . -name '*.txt' -print0 |
while IFS= read -r file; do
if a=$(head -n1 "$file" | grep -o "199[567]"); then
mv "$file" "./$a"
fi
done
find
找到一切.
- 在当前目录-name '*.txt'
- 名称以.txt
结尾
-print0
- 并将它们打印为零终止列表
|
- 管道,将一个命令的输出传递给另一个while
- 执行一个do ... done
主体直到命令 returns 非零退出状态IFS= read -r file
- 阅读零分隔列表的流行助记符,请参阅 bashfaq How can I read a file (data stream, variable) line-by-line (and/or field-by-field)?head -n1 "$file"
- 从文件中提取第一行grep
-o
- 只输出匹配的字符串199[567]
- 匹配1995
或1996
或1997
grep
如果匹配成功则输出零退出状态(在if
很重要)
a=$(...)
- 将命令的输出分配给a
。进程替换的退出状态$(...)
是最后执行的命令,在本例中为grep
。if command
- 仅当命令 return 具有非零退出状态时才执行then ... fi
主体。 IE。此处仅当 grep 成功匹配字符串时,它才会 return 零退出状态。mv "$file" "./$a"
- 变量a
(命名错误...)包含grep
匹配的字符串,因此它将是1995
或1996
或`1997。所以将文件移动到适当的文件夹。