【问题标题】:Passing shell variable to awk in for-loop在for循环中将shell变量传递给awk
【发布时间】:2021-06-21 21:10:15
【问题描述】:

我正在编写一个脚本来打印与给定字符串匹配的单元格的列号和行号,然后将其输出到文本文件。各个 awk 命令在终端中运行良好,我已经解决了其他语法问题,但输出的 .txt 仍然为空。我认为我在将 shell 变量传递给 awk 时遇到问题。

#!/bin/bash

echo Literal or regex string to find:
read string
echo File path to find string match in:
read filename

echo "Matches for $string were found in the following cells:" > results.txt

for string in filename
do
    awk -v awkvar="$string" -F"," '{for(i=1;i<=NF;i++){if ($i ~ /awkvar/){print i}}}' $filename >> results.txt | echo -e "\n" >> results.txt
    awk -v awkvar="$string" '/awkvar/{print NR}' $filename >> results.txt | echo -e "\n" >> results.txt
done

问题已解决

我重写了脚本如下:

#!/bin/bash

# Prompt for input: 1. enter file name or path that you want searched; 2. enter the literal or regex string
echo File name or path to find matches in:
read file
echo Literal or regex string to find:
read string

# Define variable and test if any matches are to be found; if not, notification is sent to terminal, but if matches exist, their row numbers (as summary rows) and individual column numbers will be output to a .txt file in the home directory. NB: you need to escape minus symbol with brackets, [-], so that it's not confused with an invalid grep option!
matchesFound=$(cat $file | grep -E -c "$string")
if [ $matchesFound -eq 0 ];
then
    echo "No matches exist."
else
    printf "Summary Row No: \n`awk -v awkvar="$string" '$0 ~ awkvar{print NR}' $file`" > results_for_$string.txt
    printf "\nInstance Column No: \n`awk -v awkvar="$string" -F"," '{for(i=1;i<=NF;i++){if ($i ~ awkvar){print i}}}' $file`" >> results_for_$string.txt
fi

【问题讨论】:

    标签: regex bash for-loop variables awk


    【解决方案1】:

    您不能在正则表达式检查模式中使用awk 变量,请尝试以下操作。您可以使用awkindex 函数并检查条件是否尝试不使用/../ 方式。

    awk -v awkvar="$string" -F"," '{for(i=1;i<=NF;i++){if ($i ~ awkvar){print i}}}' $filename >> results.txt | echo -e "\n" >> results.txt
    awk -v awkvar="$string" 'index($0,awkvar){print NR}' $filename >> results.txt | echo -e "\n" >> results.txt
    

    此答案仅处理 OP 根据问题显示的 awk 代码,以修复它。

    【讨论】:

    • 感谢指点,但输出还是空的……
    • @KayGee,正如我所提到的,我不确定您的完整要求(因为您的问题仅针对 awk 搜索),您能否仅运行 awk -v awkvar="$string" -F"," '{for(i=1;i&lt;=NF;i++){if ($i ~ awkvar){print i}}}' $filename &gt;&gt; results.txt | echo -e "\n" &gt;&gt; results.txt 将 $filename 更改为单个值并查看它在单个文件上做了什么然后让我知道?
    • 在单个文件上效果很好!谢谢!我只需要找出为什么它不能在 for 循环中工作......
    • 不要把一个普通的变量变成一个数组;直接将其作为数组读取,例如read -a filenames,然后使用for string in "${filenames[@]}"
    • @KayGee 你在一个地方有filename,在另一个地方有filenames。除此之外,循环看起来还不错,但是将awk 命令嵌入到传递给echo 命令的字符串中看起来很奇怪。可能没问题,但如果不知道更多关于它应该完成的事情,我就无法说出更多。顺便说一句,我建议通过shellcheck.net 运行您的脚本。
    猜你喜欢
    • 2014-09-09
    • 2017-04-01
    • 2014-03-11
    • 2012-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多