bash - shell编程中的命令 "grep | cut"

标签 bash shell unix grep

我在使用 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变量
  • 将一行上的值读取到 leftright 变量
  • 如果left等于right,则打印right

关于bash - shell编程中的命令 "grep | cut",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67416275/

相关文章:

bash - makefile 中的多行 bash 命令

C - 命令行解释器

c - 对套接字对的读/写是完全同步的还是有缓冲?

linux - 如何在 Windows 中运行 Matlab 中的 Unix 命令?

linux - 错误的端口号-- sftp ://11. 111.10.3

linux - 如何在 LINUX 中实现 AJAX(交互式)搜索以查找文件?

bash - 用于读取文件的 Shell 脚本帮助

c - 如何将 "*"参数传递给 main()?

linux - bash 及其引用规则的问题

python - 从另一个 python 脚本运行 python 脚本但不是作为子进程