bash - shell 脚本 : with awk, 如果找到 string0 则写入 string1,否则写入 string2

标签 bash shell awk

我有一系列的目录

079/af3
100/af4
120/af3
  . 
  .
  .

每个 ???/af? 目录包含一个很长的文件 results.stdout。接近这个文件的末尾,可以找到字符串

 Normal termination: iterations complete!

如果 af3(resp.af4)中的计算成功,否则一个或多个错误消息将写入文件。为了避免手动检查每个文件,我正在编写一个生成摘要文件的脚本:

 Massflow        af3      af4 
      079    Success  Failure
      100    Failure  Success
      120    Success  Success
        .      .       .
        .      .       .

到目前为止,我已经能够制作以下内容:

#!/bin/bash

strlen="9" # want to keep the format flexible, instead than hardcode it
format0="%"$strlen"s %"$strlen"s %"$strlen"s\n"
# write the header of file summary
awk -v format="$format0" ' BEGIN { printf format, "Massflow", "af3", "af4"
                             } ' >> summary


for dir in ??? # loop on all the directories
do
    for j in 3 4 # loop on the two subdirs
    do
    result[$j]=$(tac $dir/af$j/results.stdout | awk '
    /TACOMA:- Normal termination: iterations complete!/ {success = 1; exit}
    END { if (success == 1)
              print "Success"
          else
              print "Failure"
        }')
    done
done
exit 

但是,我不知道如何编写摘要文件...我想将 result 数组传递给另一个 awk 程序,但 awk 不接受数组变量。有什么建议么?如果您认为我的编程风格、工具选择或两者都很糟糕,请随意更改方法甚至工具:)

最佳答案

首先,不要使用 tac,因为反转整个文件没有任何好处。只需将文件提供给 awk。

您可以省略第二个for循环并保存两个结果并在之后打印它们:

for dir in ??? # loop on all the directories
do
    for j in 3 4; do
        af[$j]=$(awk '/TACOMA:- Normal termination: iterations complete!/ {success = 1; exit}
                   END { if (success == 1)
                             print "Success"
                         else
                             print "Failure"
                   }'  $dir/af$j/results.stdout)
     done

     awk -v format="$format0" "BEGIN { printf format, \"$dir\", \"${af[3]}\", \"${af[4]}\"; } " >> summary
done

来自@EdMorton 在 bash 中仅没有 awk:

for dir in ??? # loop on all the directories
do
    for j in 3 4; do
        if grep -q "TACOMA:- Normal termination: iterations complete!" "$dir/af$j/results.stdout"; then
            af[$j]="Success"
        else
            af[$j]="Failure"
        fi
     done

     printf "$format0" "$dir" "${af[3]}" "${af[4]}" >> summary
done

关于bash - shell 脚本 : with awk, 如果找到 string0 则写入 string1,否则写入 string2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13012000/

相关文章:

Jenkins Permission Denied 中的 GIT 克隆问题

regex - 删除换行符 (\n) 但排除具有特定正则表达式的行?

linux - linux中python的可执行路径错误

linux - 使用脚本外壳创建多个文件

linux - 如何从文件中的匹配行中提取子字符串?

bash - 仅获取值符合 bash 范围的行

Linux Bash 脚本

linux - 运行 bash 脚本,就好像它是从不同的目录执行的一样

mysql - 如果字段存在,则在 MySQL 和 BASH 中回显 "something",否则插入表 - 输出到变量?

mysql - 使用 Shell 脚本运行远程 MySQL 命令