我想要移动当前目录中特定扩展名的100个文件到上级目录,但我的尝试没有成功。
for file in $(ls -U | grep *.txt | tail -100)
do
mv $file ../
done
你能指导我正确的方法吗?
由于你没有引用*.txt
,Shell将其扩展为所有以.txt
结尾的文件名。所以你的命令类似于:
ls -U | grep file1.txt file2.txt file3.txt ... | tail -100
grep
带有文件名参数,因此它会忽略标准输入。它输出所有与 file1.txt
匹配的行在其余的文件中。可能没有匹配,所以没有东西被传送到 tail -100
。即使有匹配,输出也将是文件中的行而不是文件名,因此对于 mv
命令没有用。
您可以直接循环遍历文件名,并使用计数器变量在 100 个文件后停止。
counter=0
for file in *.txt
do
if (( counter >= 100 ))
then break
fi
mv "$file" ../
((counter++))
done
ls
的输出所带来的问题。这个可以完成任务:
ls -U *.txt | tail -100 | while read filename; do mv "$filename" ../; done
while read filename
保留文件名中的空格。
ls
命令的 -U
参数。此外,我不太清楚这个解决方案在哪些方面比 OP 提出的更好。 - user1934428grep
。 - Barmar在文本文件目录中运行此命令:
#!/bin/bash
for txt_file in ./*.txt; do
((c++==100)) && break
mv "$txt_file" ../
done
grep *.txt
is not correct, since the shell expands the wildcard. Usels *.txt
- Barmarls
的输出是一个臭名昭著的陷阱。用户应该依赖于find
。 - Enlicotail -100
的解决方案都会遇到类似的问题。 - Barmar