在一个目录中,您有一些不同的文件-. txt
、.sh
,然后计划没有.foo
修饰符的文件。
如果您ls
目录:
blah.txt
blah.sh
blah
blahs
如何告诉for循环只使用没有. foo
修改的文件?所以在上面的示例中对文件blah和blah进行“做东西”。
基本语法是:
#!/bin/bash
FILES=/home/shep/Desktop/test/*
for f in $FILES
do
XYZ functions
done
如您所见,这有效地循环了目录中的所有内容。如何排除. sh
、.txt
或任何其他修饰符?
我一直在玩一些if语句,但我真的很好奇我是否可以选择那些未修改的文件。
也有人能告诉我这些没有. txt的纯文本文件的正确行话吗?
#!/bin/bash
FILES=/home/shep/Desktop/test/*
for f in $FILES
do
if [[ "$f" != *\.* ]]
then
DO STUFF
fi
done
如果你想让它更复杂一点,你可以使用find-命令。
对于当前目录:
for i in `find . -type f -regex \.\\/[A-Za-z0-9]*`
do
WHAT U WANT DONE
done
解释:
find . -> starts find in the current dir
-type f -> find only files
-regex -> use a regular expression
\.\\/[A-Za-z0-9]* -> thats the expression, this matches all files which starts with ./
(because we start in the current dir all files starts with this) and has only chars
and numbers in the filename.
http://infofreund.de/bash-loop-through-files/
您可以使用负通配符?过滤掉它们:
$ ls -1
a.txt
b.txt
c.png
d.py
$ ls -1 !(*.txt)
c.png
d.py
$ ls -1 !(*.txt|*.py)
c.png