在Bash中循环遍历特定名称的目录中的所有文件

3

我正在尝试编写一段脚本,以测试我的文件是否完全符合要求,但我以前没有使用过bash:

 #!/bin/bash
./myfile <test.in 1>>test.out 2>>testerror.out
if cmp -s "test.out" "pattern.out"
    then
        echo "Test matches pattern"
    else
        echo "Test does not match pattern"
    fi
if cmp -s "testerror.out" "pattern.err"
    then
        echo "Errors matches pattern"
    else
        echo "Errors does not match pattern"
    fi

我能否这样编写代码,执行"./script.sh myfile pattern" 后程序会运行在所有名为pattern*.in的文件上,并检查myfile是否生成了与pattern*.out和pattern*.err文件相同的结果?例如,有文件pattern1、pattern2、pattern4需要测试,但没有pattern3。

如果我不需要创建新文件,我是否可以绕过这一步骤?(假设我并不需要它们)如果我从命令行操作,我会采取类似以下的方式:

< pattern.in ./myfile | diff -s ./pattern.out

但我不知道如何在脚本文件中编写它,以使其正常工作。

或者也许我应该每次都使用rm命令?


使用 for 循环遍历与模式匹配的所有文件。 - Barmar
for file in pattern*.in - Barmar
您可以像这样使用变量:< "$file" ./myfile - Barmar
欢迎来到本站!请查看tourhow-to-ask page,了解更多有关提问的信息,以吸引高质量的回答。您可以编辑您的问题以包含更多信息。您是指想要将myfilepattern作为命令行参数提供给script.sh吗? - cxw
1个回答

1

如果我理解你的意思正确:

for infile in pattern*.in ; do  
    outfile="${infile%.in}.out"
    errfile="${infile%.in}.err"

    echo "Working on input $infile with output $outfile and error $errfile"
    ./myfile <"$infile" >>"$outfile" 2>>"$errfile"
    # Your `if`..`fi` blocks here, referencing infile/outfile/errfile
done

% 替换操作符会从变量值的末尾剥离出一个子字符串。因此,如果 $infilepattern.in,那么 ${infile%.in} 就是去掉结尾的 .in 后面剩下的 pattern。在 outfileerrfile 的赋值中也用到了这个操作符,用于复制特定的 .in 文件的第一部分(例如 pattern1)。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接