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



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

目录/dir look_like 中的文件

ABC_YYYYMDD_EF.txt
GHI_YYYYMDD_LM.txt

列表中有类似的名称

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

所以必须忽略YYYYMMDD,它可以是这种格式的任何日期,有人能告诉我们应该使用grep还是regex,以及
如何像输出:\

ABC_EF   FOUND
GHI_LM   FOUND
PQR_ST   NOT FOUND

感谢

$ 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 '%st%sFOUNDn' "$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

使用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 

相关内容

  • 没有找到相关文章

最新更新