for 使用 Bash 循环遍历目录中的特定文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14823830/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
for loop over specific files in a directory using Bash
提问by jon_shep
In a directory you have some various files - .txt
, .sh
and then plan files without a .foo
modifier.
在一个目录中,您有一些不同的文件 - .txt
,.sh
然后计划没有.foo
修饰符的文件。
If you ls
the directory:
如果你ls
的目录:
blah.txt
blah.sh
blah
blahs
How do I tell a for-loop to only use files without a .foo
modify? So "do stuff" on files blah and blahs in the above example.
我如何告诉 for 循环只使用没有.foo
修改的文件?所以在上面的例子中对文件 blah 和 blahs 进行“做事”。
The basic syntax is:
基本语法是:
#!/bin/bash
FILES=/home/shep/Desktop/test/*
for f in $FILES
do
XYZ functions
done
As you can see this effectively loops over everything in the directory. How can I exclude the .sh
, .txt
or any other modifier?
如您所见,这有效地循环了目录中的所有内容。如何排除.sh
,.txt
或任何其他修饰符?
I have been playing with some if statements but I am really curious if I can select for those non modified files.
我一直在玩一些 if 语句,但我真的很好奇是否可以选择那些未修改的文件。
Also could someone tell me the proper jargon for these plain text files without .txt?
也有人可以告诉我这些没有 .txt 的纯文本文件的正确行话吗?
回答by David Kiger
#!/bin/bash
FILES=/home/shep/Desktop/test/*
for f in $FILES
do
if [[ "$f" != *\.* ]]
then
DO STUFF
fi
done
回答by chris2k
If you want it a little bit more complex, you can use the find-command.
如果你想让它更复杂一点,你可以使用 find-command。
For the current directory:
对于当前目录:
for i in `find . -type f -regex \.\/[A-Za-z0-9]*`
do
WHAT U WANT DONE
done
explanation:
解释:
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.
回答by Blender
You can use negative wildcards? to filter them out:
您可以使用否定通配符吗?过滤掉它们:
$ ls -1
a.txt
b.txt
c.png
d.py
$ ls -1 !(*.txt)
c.png
d.py
$ ls -1 !(*.txt|*.py)
c.png