首页 > 解决方案 > 将 AWK 用于循环内的变量

问题描述

所以我从我的另一个团队那里得到了一些 URL,我需要在那个 URL 中识别一个定义的模式,并将模式后面的值保存在一个变量中。

这可以实现吗?

**Input file: Just an example**
https://stackoverflow.com/questions/hakuna
https://stackoverflow.com/questions/simba

为此,我编写了一个简单的 for 循环

for i in `cat inputFile`
do
    storeVal=awk -v $i -F"questions/" '{print$2}'
    echo "The Name for the day is ${storeVal}"
    length=`secondScript.sh ${storeVal}`
    if [[ $length -gt 10 ]]
    then
        thirdScript.sh ${storeVal}
    elif [[ $length -lt 10 ]]
    then
        fourthScript.sh ${storeVal}
    else
        echo "The length of for ${storeVal} is undefined"
done

期望的输出:

The Name for the day is hakuna
The length of for hakuna is greater than 10
Command1 hakuna executed
Command2 hakuna executed

The Name for the day is simba
Command1 simba executed
Command2 simba executed

还有一点需要注意。

我需要将 awk cut 值存储在变量中的原因是因为我需要在循环的多个位置使用该变量。

标签: bashawk

解决方案


由于听起来您想为输入文件中的每一行运行一个命令,因此您可以使用 shell 的内置功能:

while IFS=/ read -ra pieces; do
  printf '%s\n' "${pieces[@]}" # prints each piece on a separate line
done < inputFile

如果您总是想要每行 url 的最后一部分(即最后一部分之后/),那么您可以使用"${pieces[-1]}"

while IFS=/ read -ra pieces; do
  variable=${pieces[-1]} # do whatever you want with this variable
  printf 'The Name for the day is %s\n' "$variable" # e.g. print it
done < inputFile

推荐阅读