I have text file with values as:

1 Peter
2 Paul

I need a command/scipt that will take as a parameter value from the second column (e.g. Paul) and return the corresponding value from the first one (2).

I'm trying to use while loop, but how can find the value I need:

while IFS= read -a line; do      
  printf "%s\n" "${line[@]}"     
done < "file.txt"

With GNU grep:

grep -Po ".* (?=Paul)" file



or with bash:

while read -r num name; do
  [[ $name == "Paul" ]] && printf "%s\n" "$num"
done < file

awk might come in handy in this scenario:

$ awk '$2 == "Paul" {print $1}' input.txt

Or interactively:

$ awk 'BEGIN{printf "Name: "; getline name < "-"} $2 == name {print $1}' input.txt
Name: Paul

You may grep it first, then read the values, e.g.

grep -w Paul file.txt | while read v k; do echo $v; done

If you know Paul is the last column, use Paul$.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.