【问题标题】:Bash Shell Scripting assigning new variables for output of a grep searchBash Shell 脚本为 grep 搜索的输出分配新变量
【发布时间】:2017-06-26 15:51:45
【问题描述】:

编辑 2: 为了更好地描绘我的结果,我决定重写它。

我目前正在使用此代码来输出各个目录中的文件列表:

for file in /directoryX/*.txt

do
     grep -rl "Annual Compensation" $file
done

输出显示了所有具有我试图以这样的布局提取的特定表的文件:

txtfile1.txt
txtfile2.txt
txtfile3.txt

我一直在对每个单独的 .txt 文件使用此 awk 命令来提取表,然后将其发送到 .csv:

awk '/Annual Compensation/{f=1} f{print; if (/<\/TABLE>/) exit}' txtfile1.txt > txtfile1.csv

我的目标是找到一个命令,它可以同时针对列表中的每个文件运行我的 awk 命令。感谢那些已经提供建议的人。

【问题讨论】:

  • 我无法理解您的要求。 CSV 文件包含什么内容?
  • 抱歉,我无法理解您的问题。您能否提供更多背景和更多细节,尤其是关于所需的输出/效果?
  • 我会先尝试在诸如 output=`grep -rl "Annual Compensation" $file` 这样的行中使用倒撇号 ('`'),然后看看我能用 $output 做什么.
  • 或者您可以加入 90 年代并使用语法 var=$(grep -rl "Annual Compensation" "$file") ;-) 的“现代”命令替换。祝大家好运!

标签: bash macos for-loop grep


【解决方案1】:

如果我理解您的要求,我认为您想要做的是在 grep 之后添加一行,或者代替 grep,它表示:

awk '/Annual Compensation/{f=1} f{print; if (/<\/TABLE>/) exit}' $file > ${file}_new.csv

当您说${file}_new.csv 时,它会扩展file 变量,然后将字符串“_new.csv”添加到其中。这就是你的目标,对吧?

【讨论】:

    【解决方案2】:

    修改你的代码:

    for file in /directoryX/*.txt
    do
        files+=($(grep -rl "Annual Compensation" $file))
    done
    
    for f in "${files[@]}";do
        awk '/Annual Compensation/{f=1} f{print; if (/<\/TABLE>/) exit}' "$f" > "$f"_new.csv
    done
    

    替代代码:

    files+=($(grep -rl "Annual Compensation" /directoryX/*))
    for f in "${files[@]}";do
    awk '/Annual Compensation/{f=1} f{print; if (/<\/TABLE>/) exit}' "$f" > "$f"_new.csv
    

    在这两种情况下,我都没有验证 grep 结果和 awk 结果 - 这只是您的代码的复制粘贴。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-04-10
      • 1970-01-01
      • 2012-06-18
      • 1970-01-01
      • 1970-01-01
      • 2021-08-22
      • 1970-01-01
      相关资源
      最近更新 更多