我在使用 grep
命令时遇到问题。
我有一个名为 dictionary.txt 的文件,其中包含 2 列单词,例如
abc def
apple orange
hour minute
在我的 Bash 脚本中,在左列中输入单词作为参数后,我必须使用 grep
命令在右侧输出相应的单词。
要求是使用循环。
我创建了这个脚本:
#!/bin/bash
parola=$1
for traduzione in $( sort dictionary.txt )
do
if [ $parola == $traduzione ]
then
grep $traduzione | cut -f 2 dictionary.txt
fi
done
这并不像上面描述的那样工作。
最佳答案
我建议将整个 for
循环替换为
awk -v word="$parola" '$1 == word{print $2;exit}' dictionary.txt
哪里
-v word="$parola"
将parola
变量传递给 awk 脚本$1 == word
检查第 1 列值是否等于parola
{print $2;exit}
- 打印 Column2 值并退出(如果您需要后续行中的所有匹配项,请删除exit
)。
使用dictionary.txt
作为
abc def
apple orange
hour minute
和script.sh
为
#!/bin/bash
parola=$1
awk -v word="$parola" '$1 == word{print $2; exit}' dictionary.txt
bash script.sh apple
返回橙色
。
如果您需要 for
循环,可以使用
#!/bin/bash
parola=$1
while IFS= read -a line; do
read -r left right <<< "$line"
if [ "$left" == "$parola" ]; then
echo "$right";
fi
done < dictionary.txt
即:
- 逐行读取
dictionary.txt
,并将当前行值分配给line
变量 - 将一行上的值读取到
left
和right
变量 - 如果
left
等于right
,则打印right
。
关于bash - shell编程中的命令 "grep | cut",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67416275/