【问题标题】:Search if file exists for a file pattern stored in array搜索存储在数组中的文件模式是否存在文件
【发布时间】:2015-02-21 08:50:55
【问题描述】:

我有两个数组,一个是要搜索的文件路径,另一个是要搜索的文件。例如 searchfile.dat 将有 文件: abc303 xyz123

我必须搜索可能是 abc303*.dat 或任何扩展名的文件。 abc303*.dat.gz

如果我给出 * 以下代码不起作用,它只有在我给出要在 searchfile.dat 中搜索的确切文件名时才起作用,我也尝试不带引号和不带反斜杠。

我正在使用 ksh

while [[ $i -lt ${#filearray[@]}  ]];do
while [[ $j -lt ${#filepath[@]} ]];do
found=0
if [[ -a  "${filepath[$j]}/${filearray[$i]}"\* ]]; then
echo ${filepath[$j]}/${filearray[$i]} "found"

【问题讨论】:

  • 请帮助我们提供填充数组的代码并提供完整的代码(包括 (( i = i + 1 ))、(( j = j + 1 ))、fi/done/done) .并显示echo ${filepath[$j]}/${filearray[$i]}的结果
  • 嗨,我无法将整个代码放在评论中,因此发布为答案。

标签: arrays file search ksh


【解决方案1】:

这里是代码

#!/usr/bin/ksh
set -A filearray $(cat searchfile.dat)
fp1=/home/n221/fp1
fp2=/home/n221/fp2

set -A filepath $fp1 $fp2 $fp3
i=0
j=0
while [[ $i -lt ${#filearray[@]}  ]];do
while [[ $j -lt ${#filepath[@]} ]];do
found=0
echo ${filepath[$j]}/${filearray[$i]} "${filepath[$j]}/${filearray[$i]}"
if [[ -a "${filepath[$j]}/${filearray[$i]}"\* ]]; then    
echo ${filepath[$j]}/${filearray[$i]} "found"
found=1
elif [[ $found -eq 0 ]]; then
echo ${filearray[$i]} "not found in " ${filepath[$j]}
fi
(( j=j+1 ))
done
found=5
j=0
(( i=i+1 ))
done

输出

${filepath[$j]}/${filearray[$i]}  /home/n221/fp1/b.dat
b.dat not found in  /home/n221/fp1
${filepath[$j]}/${filearray[$i]}  /home/n221/fp2/b.dat
b.dat not found in  /home/n221/fp2

我在 /home/n221/fp1 路径中放置了一个 b.dat.gz 文件 在 searchfile.dat 中我放置了“d.dat”

【讨论】:

    【解决方案2】:

    主要问题是测试if [[ -a "${filepath[$j]}/${filearray[$i]}"\* ]]
    双方括号有特殊含义,你的脚本更适合

    if [ -a "${filepath[$j]}/${filearray[$i]}"\* ]
    

    我对通配符不是很满意,但是当你有超过 1 个文件时它仍然有效。

    我会避免这样的数组:

    #!/usr/bin/ksh
    fp1=/home/n221/fp1
    fp2=/home/n221/fp2
    
    filepath="$fp1 $fp2 $fp3"
    i=0
    j=0
    cat searchfile.dat | while read file; do
            for path in  ${filepath}; do
                    found=0
                    echo Searching ${path}/${file}
                    if [ -a "${path}/${file}"* ]; then
                            echo ${file}/${file} "found"
                            found=1
                    elif [[ $found -eq 0 ]]; then
                            echo ${file} "not found in " ${path}
                    fi
                    (( j=j+1 ))
            done
            found=5
            j=0
            (( i=i+1 ))
    done
    

    也许你可以用 find 来避免循环,从

    filepath="$fp1 $fp2 $fp3"
    filebases="-name b.dat* -o -name notfound.dat* -o -name otherfile.dat*"
    find ${filepath} ${filebases}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-01
      • 2010-10-16
      • 2010-10-22
      相关资源
      最近更新 更多