代码之家  ›  专栏  ›  技术社区  ›  dreamlax

用shell脚本筛选目录列表

  •  1
  • dreamlax  · 技术社区  · 16 年前

    如果我有一个bash变量:

    Exclude="somefile.txt anotherfile.txt"
    

    如何获取目录的内容,但将上述内容排除到列表中的文件中?我希望能够做一些事情,比如:

    Files=  #some command here
    someprogram ${Files}
    

    someprogram 应该给特定目录中的所有文件,除了 ${Exclude} 变量。修改 一些程序 不是选项。

    4 回复  |  直到 16 年前
        1
  •  2
  •   Hugo Peixoto    16 年前

    我不确定您是否接受过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[@]}
    

    注意,我用双引号将exclude中的每个文件名都括起来,并添加了 它们周围有圆括号。替换 echo 具有 someprogram ,更改ls命令 到你想要检查的目录,你应该让它工作。 这个 comm 程序是关键。

        2
  •  1
  •   ogrodnek    16 年前

    您可以使用“查找”。类似:

    FILES=`find /tmp/my_directory -type f -maxdepth 1 -name "*.txt" -not -name somefile.txt -not -name anotherfile.txt`
    

    其中/tmp/my_目录是要搜索的路径。

    如果您想用一个简单的for循环,可以从excludes中构建“-not-name blah-not-name blah2”列表…

        3
  •  0
  •   Brian Pellin    16 年前

    以下是标准UNIX命令行的一行程序:

    LS GREP-V“^$排除$”xargs

    它确实有一个假设。$exclude需要正确转义,这样类似字符的句点就不会被解释为regex的一部分。

        4
  •  0
  •   Dimitre Radoulov    16 年前

    假设文件名没有空格或其他病理特征:

    shopt -s extglob
    Files=(!(@(${Exclude// /|})))