我需要删除当前目录中除一个文件(例如abc.txt)外的所有文件。是否有任何命令可以删除目录中除abc.txt之外的其他文件?
rm !(abc.txt)
This will run rm
on all entries in the directory (apart from "abc.txt") and this includes subdirectories. You will therefore end up with the "cannot remove directory" error if subdirs exist. If this is the case, use find
instead:
find . -maxdepth 1 -type f \! -name "abc.txt" -exec rm {} \;
# omit -maxdepth 1 if you also want to delete files within subdirectories.
If !(abc.txt)
returns a very long list of files, you will potentially get the infamous "argument list too long" error. Again, find
would be the solution to this issue.
rm !(abc.txt)
will fail if the directory is empty or if abc.txt is the only file. Example:
[me@home]$ ls
abc.txt
[me@home]$ rm !(abc.txt)
rm: cannot remove `!(abc.txt)': No such file or directory
You can workaround this using nullglob, but it can often be cleaner to simply use find
. To illustrate, a possible workaround would be:
shopt -s nullglob
F=(!(abc.txt)); if [ ${#F[*]} -gt 0 ]; then rm !(abc.txt); fi # not pretty
set +H
来暂时禁用历史命令。 - Shawn Chinrm -rf ...
,除非我确切知道它将匹配哪些文件。一旦失误,你可能会删除更多的文件。 - Shawn Chin1)
mv abc.txt ~/saveplace
rm *
mv ~/saveplace/abc.txt .
2)
find . ! -name abc.txt -exec rm {} "+"
尝试
find /your/dir/here -type f ! -name abc.txt -exec rm {} \;
如果文件名中没有空格,您可以使用for
循环遍历ls
的结果:
for FILE in `ls -1`
do
if [[ "$FILE" != "abc.txt" ]]; then
rm $FILE
fi
done
你可以将它写成脚本,或者直接在bash提示符下编写:先写第一行,然后按下enter
键,接着你可以写其他行,bash会等待你写完done
再执行。否则,你可以将其写成单行:
for FILE in `ls -1`; do if [[ "$FILE" != "abct.txt" ]]; then rm $FILE; fi; done