Alessio Scalzo
Alessio Scalzo

Reputation: 45

Command "grep | cut" in shell programming

I have a problem with the grep command.

I have a file, called dictionary.txt, containing 2 columns of words, like

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.

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.

Upvotes: 2

Views: 1128

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626758

I'd suggest to replace the whole for loop with

awk -v word="$parola" '$1 == word{print $2;exit}' dictionary.txt

where

  • -v word="$parola" passes the parola variable to the awk script
  • $1 == word checks if the Column 1 value equals the parola
  • {print $2;exit} - prints the Column2 value and exits (remove exit if you need all matches on the further lines).

With dictionary.txt as

abc def
apple orange
hour minute

and script.sh as

#!/bin/bash
parola=$1
awk -v word="$parola" '$1 == word{print $2; exit}' dictionary.txt

the bash script.sh apple returns orange.

If you need a for loop you can use


#!/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
  • Read the values on a line into left and right variables
  • If left is equal to right, print right.

Upvotes: 2

Dominique
Dominique

Reputation: 17493

Why are you using a for-loop?

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 your information, -w means "only take whole words".

Upvotes: 0

Related Questions