bash 使用 shell 脚本过滤目录列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/628564/
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
Filter directory listing with shell script
提问by dreamlax
If I have a BASH variable:
如果我有一个 BASH 变量:
Exclude="somefile.txt anotherfile.txt"
How can I get the contents of a directory but exclude the above to files in the listing? I want to be able to do something like:
如何获取目录的内容但将上述内容排除在列表中的文件中?我希望能够执行以下操作:
Files= #some command here
someprogram ${Files}
someprogramshould be given all of the files in a particular directory, except for those in the ${Exclude}variable. Modifying someprogramis not an option.
someprogram应该给出特定目录中的所有文件,${Exclude}变量中的文件除外。修改someprogram不是一个选项。
回答by Hugo Peixoto
I'm not sure if you were taking about unix shell scripting, but here's a working example for bash:
我不确定您是否正在使用 unix shell 脚本,但这里有一个适用于 bash 的示例:
#!/bin/bash
Exclude=("a" "b" "c")
Listing=(`ls -1Q`)
Files=( $(comm -23 <( printf "%s\n" "${Listing[@]}" ) <( printf "%s\n" "${Exclude[@]}"
) ) )
echo ${Files[@]}
Note that I enclosed every filename in Exclude with double quotes and added
parenthesis around them. Replace echowith someprogram, change the ls command
to the directory you'd like examined and you should have it working.
The commprogram is the key, here.
请注意,我用双引号将 Exclude 中的每个文件名括起来,并在它们周围添加了括号。替换echo为someprogram,将 ls 命令更改为您要检查的目录,并且您应该让它工作。该comm项目是关键,在这里。
回答by ogrodnek
You can use find. something like:
您可以使用查找。就像是:
FILES=`find /tmp/my_directory -type f -maxdepth 1 -name "*.txt" -not -name somefile.txt -not -name anotherfile.txt`
where /tmp/my_directory is the path you want to search.
其中 /tmp/my_directory 是您要搜索的路径。
You could build up the "-not -name blah -not -name blah2" list from Excludes if you want with a simple for loop...
如果你想用一个简单的 for 循环,你可以从 Excludes 建立“-not -name blah -not -name blah2”列表......
回答by Brian Pellin
Here's a one liner for a standard Unix command line:
这是标准 Unix 命令行的单行代码:
ls | grep -v "^${Exclude}$" | xargs
ls | grep -v "^${排除}$" | 参数
It does have one assumption. ${Exclude} needs to be properly escaped so charaters like period aren't interpreted as part of the regex.
它确实有一个假设。${Exclude} 需要正确转义,因此像句号这样的字符不会被解释为正则表达式的一部分。
回答by Dimitre Radoulov
Assuming filenames with no spaces or other pathological characters:
假设文件名没有空格或其他病态字符:
shopt -s extglob
Files=(!(@(${Exclude// /|})))

