[英]Command "grep | cut" in shell programming
I have a problem with the grep
command.我对
grep
命令有疑问。
I have a file, called dictionary.txt , containing 2 columns of words, like我有一个名为dictionary.txt的文件,其中包含 2 列单词,例如
abc def
apple orange
hour minute
In my Bash script, having entered the word in the left column as an argument, I have to output the corresponding word on the right using the grep
command.在我的 Bash 脚本中,在左栏中输入了单词作为参数后,我必须使用
grep
命令在右侧 output 对应的单词。
A requirement is to use a loop.一个要求是使用循环。
I created this script:我创建了这个脚本:
#!/bin/bash
parola=$1
for traduzione in $( sort dictionary.txt )
do
if [ $parola == $traduzione ]
then
grep $traduzione | cut -f 2 dictionary.txt
fi
done
This does not work as described above.如上所述,这不起作用。
I'd suggest to replace the whole for
loop with我建议将整个
for
循环替换为
awk -v word="$parola" '$1 == word{print $2;exit}' dictionary.txt
where在哪里
-v word="$parola"
passes the parola
variable to the awk script -v word="$parola"
将parola
变量传递给 awk 脚本$1 == word
checks if the Column 1 value equals the parola
$1 == word
检查第 1 列的值是否等于parola
{print $2;exit}
- prints the Column2 value and exits (remove exit
if you need all matches on the further lines). {print $2;exit}
- 打印 Column2 值并退出(如果您需要其他行上的所有匹配项,请删除exit
)。 With dictionary.txt
as用
dictionary.txt
作为
abc def
apple orange
hour minute
and script.sh
as和
script.sh
作为
#!/bin/bash
parola=$1
awk -v word="$parola" '$1 == word{print $2; exit}' dictionary.txt
the bash script.sh apple
returns orange
. bash script.sh apple
返回orange
。
If you need a for
loop you can use如果你需要一个
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
That is:那是:
dictionary.txt
line by line assigning the current line value to the line
variabledictionary.txt
,将当前行值赋给line
变量left
and right
variablesright
left
left
is equal to right
, print right
.left
等于right
,则打印right
。 Why are you using a for
-loop?为什么要使用
for
循环?
grep -w "word1" dictionary.txt
This shows you the line where you can find that word, so the for
-loop is not even needed.这会向您显示可以找到该单词的行,因此甚至不需要
for
循环。 For your information, -w
means "only take whole words".供您参考,
-w
表示“只取整个单词”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.