28

在一个目录中,您有一些不同的文件 - .txt.sh然后计划没有.foo修饰符的文件。

如果你ls的目录:

blah.txt
blah.sh
blah
blahs

如何告诉 for 循环仅使用文件而不进行.foo修改?所以在上面的例子中对文件 blah 和 blahs “做一些事情”。

基本语法是:

#!/bin/bash
FILES=/home/shep/Desktop/test/*

for f in $FILES
do
    XYZ functions
done

如您所见,这有效地循环了目录中的所有内容。如何排除.sh,.txt或任何其他修饰符?

我一直在玩一些 if 语句,但我真的很好奇我是否可以选择那些未修改的文件。

也有人可以告诉我这些没有 .txt 的纯文本文件的正确术语吗?

4

3 回答 3

36
#!/bin/bash
FILES=/home/shep/Desktop/test/*

for f in $FILES
do
if [[ "$f" != *\.* ]]
then
  DO STUFF
fi
done
于 2013-02-12T01:10:06.823 回答
12

如果你想让它更复杂一点,你可以使用 find-command。

对于当前目录:

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/

于 2014-08-18T21:55:01.510 回答
2

可以使用负通配符吗?过滤掉它们:

$ ls -1
a.txt
b.txt
c.png
d.py
$ ls -1 !(*.txt)
c.png
d.py
$ ls -1 !(*.txt|*.py)
c.png
于 2013-02-12T01:05:59.083 回答