用于迭代目录和模式匹配文件名中的文件的 Bash 脚本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11185771/
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
Bash script to iterate files in directory and pattern match filenames
提问by Homunculus Reticulli
I need to process a large number of files in a directory. The files can be partitioned into several groups, based upon the file names. That is to say, the file names can be pattern matchedne which 'group' they belong to. For instance, the names are like this:
我需要处理目录中的大量文件。可以根据文件名将文件分成几个组。也就是说,文件名可以模式匹配它们属于哪个“组”。例如,名称是这样的:
- YYYYMMDD_*_bulk_import.csv
- YYYYMMDD_*_genstats_import.csv
- YYYYMMDD_*allstats.csv
- YYYYMMDD_*_bulk_import.csv
- YYYYMMDD_*_genstats_import.csv
- YYYYMMDD_*allstats.csv
etc ...
等等 ...
Each 'group' has a different processing methodology (i.e. a different command is called for processing).
每个“组”都有不同的处理方法(即调用不同的命令进行处理)。
I want to write a bash script to:
我想写一个 bash 脚本来:
- Iterate through all CSV files in the directory
- Determine which 'group' a file belongs to by pattern matching its name to known patterns (like the examples I gave above)
- Call a command based on the determined grouping.
- 遍历目录中的所有 CSV 文件
- 通过将文件名称与已知模式匹配的模式来确定文件属于哪个“组”(如我上面给出的示例)
- 根据确定的分组调用命令。
I am running on Ubuntu 10.0.4. I am new to bash, and would appreciate skeleton code snippet that will help me get started in writing this script.
我在 Ubuntu 10.0.4 上运行。我是 bash 的新手,希望能够帮助我开始编写此脚本的骨架代码片段。
回答by cdhowie
The easiest way is probably just to iterate each group separately. This side-steps the parsing issue entirely.
最简单的方法可能只是分别迭代每个组。这完全回避了解析问题。
DIRECTORY=.
for i in $DIRECTORY/YYYYMMDD_*_bulk_import.csv; do
# Process $i
done
for i in $DIRECTORY/YYYYMMDD_*_genstats_import.csv; do
# Process $i
done
for i in $DIRECTORY/YYYYMMDD_*allstats.csv; do
# Process $i
done
Set DIRECTORY
to whatever directory you want to search. The default .
will search the current working directory.
设置DIRECTORY
为您要搜索的任何目录。默认.
将搜索当前工作目录。
回答by jazgot
Here is basic iteration over files, with switch block to determine file type.
这是对文件的基本迭代,使用 switch 块来确定文件类型。
#!/bin/bash
for f in *; do
case $f in
[0-9]*_bulk_import.csv)
echo $f case 1
;;
[0-9]*_genstats_import.csv)
echo $f case 2
;;
[0-9]*allstats.csv)
echo $f case 3
;;
esac
done