使用Bash循环遍历目录中的特定文件

jon*_*hep 26 bash for-loop

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

如果你ls的目录:

blah.txt
blah.sh
blah
blahs
Run Code Online (Sandbox Code Playgroud)

如何告诉for循环只使用没有.foo修改的文件?因此,在上面的例子中,对文件进行"处理"等等.

基本语法是:

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

for f in $FILES
do
    XYZ functions
done
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,这有效地遍历目录中的所有内容.我怎样才能排除.sh,.txt或其他任何修改?

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

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

Dav*_*ger 34

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

for f in $FILES
do
if [[ "$f" != *\.* ]]
then
  DO STUFF
fi
done
Run Code Online (Sandbox Code Playgroud)


小智 12

如果您希望它更复杂一些,可以使用find-command.

对于当前目录:

for i in `find . -type f -regex \.\\/[A-Za-z0-9]*`
do
WHAT U WANT DONE
done
Run Code Online (Sandbox Code Playgroud)

说明:

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.
Run Code Online (Sandbox Code Playgroud)

http://infofreund.de/bash-loop-through-files/