2

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"

3 Answers 3

3

With GNU grep:

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

Output:

2

or with bash:

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

awk might come in handy in this scenario:

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

Or interactively:

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

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$.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .