繁体   English   中英

如何使用正则表达式或 bash 脚本中的 grep 检查目录中文件名列表中的特定文件是否存在

[英]How to check if particular files from list of filenames present in directory with regex or grep in bash script

需要编写脚本来检查目录中是否存在特定文件列表

目录 /dir 中的文件看起来像

ABC_YYYYMMDD_EF.txt
GHI_YYYYMMDD_LM.txt

并且列表的名称如下

l=[ABC_EF, GHI_LM,PQR_ST,..]

所以必须忽略 YYYYMMDD ,它可以是这种格式的任何日期,谁能告诉我们应该使用 grep 还是正则表达式以及如何
像 output:\

ABC_EF   FOUND
GHI_LM   FOUND
PQR_ST   NOT FOUND

谢谢

使用 awk:

awk -v lst="ABC_EF,GHI_LM,PQR_ST" '
    BEGIN { 
            split(lst,map,",") # split the passed variable lst in an array map, using the function split and the delimiter ,
          } 
    END { 
            for (i in map) { # Loop through each entry in the map array
                             split(map[i],map1,"_"); # Further split the map values in map1 using _ as the delimiter
                             res=""; # Initialise a res variable
                             "find . -maxdepth 1 -regextype posix-extended -regex \"^.*"map1[1]"_.*[[:digit:]]+.*_"map1[2]".txt\"" | getline res; # Execute a find command and register the result in res using getline
                             if (res !="") { 
                                             print map[i]" FOUND" # If res is not empty, print FOUND, otherwise NOT FOUND.
                                           } 
                                      else { 
                                             print map[i]" NOT FOUND"
                                            } 
                              close("find . -maxdepth 1 -regextype posix-extended -regex \"^.*"map1[1]"_[[:digit:]]{8}_"map1[2]".txt\"") # Close the pipe
                              } 
                            }' <<< /dev/null

一个班轮:

awk -v lst="ABC_EF,GHI_LM,PQR_ST" 'BEGIN { split(lst,map,",") } END { for (i in map) { split(map[i],map1,"_");res="";"find . -maxdepth 1 -regextype posix-extended -regex \"^.*"map1[1]"_.*[[:digit:]]+.*_"map1[2]".txt\"" | getline res;if (res !="") { print map[i]" FOUND" } else { print map[i]" NOT FOUND"} close("find . -maxdepth 1 -regextype posix-extended -regex \"^.*"map1[1]"_[[:digit:]]{8}_"map1[2]".txt\"") } }' <<< /dev/null 
$ cat tst.sh
#!/usr/bin/env bash

shopt -s extglob nullglob

dir="$1"

names=( ABC_EF GHI_LM PQR_ST )
for name in "${names[@]}"; do
    files=( "${dir}/${name%_*}_"+([0-9])"_${name#*_}.txt" )
    (( ${#files[@]} )) && result="" || result="NOT "
    printf '%s\t%sFOUND\n' "$name" "$result"
done

$ ls tmp
ABC_19001231_EF.txt  GHI_20200102_LM.txt

$ ./tst.sh tmp
ABC_EF  FOUND
GHI_LM  FOUND
PQR_ST  NOT FOUND

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM