bash - 将 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 值存储在变量中的原因是因为我需要在循环的多个位置使用该变量。
解决方案
由于听起来您想为输入文件中的每一行运行一个命令,因此您可以使用 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
推荐阅读
- mysql - MySql Error code: 1093- You can't specify target table 'n1' for update in FROM clause
- python - 切换程序时如何使未停靠的QDockWidget保持可见?
- vb.net - 应用程序从 Global.System.Configuration.DefaultSettingValueAttribute 而不是 app.config 获取连接字符串
- vue.js - Vuetify - 防止 v-list-item-group 取消选择
- json - 控制字符错误,可能编码不正确
- android - 如何在 Android 中创建一个底部切割的半椭圆形按钮?
- python - 在 16 页段中合并 2 个 PDF
- c++ - 为什么适配器兼容的函数对象不能作为参考传递参数?
- nginx - 如何使用 nginx (https) 将请求转发到其他 docker 服务
- java - 有条件地返回 Java ArrayList 中每个 Nth 对象的属性之和的方法