简体   繁体   English

shell 编程中的命令“grep | cut”

[英]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 asdictionary.txt作为

abc def
apple orange
hour minute

and script.sh asscript.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:那是:

  • Read dictionary.txt line by line assigning the current line value to the line variable逐行读取dictionary.txt ,将当前行值赋给line变量
  • Read the values on a line into left and right variables将一行right left
  • If 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM