3
#!/bin/bash

cat /home/user/list
read -p "enter a number: " LISTNUMBER
USERNAME=$(awk '$LISTNUMBER {
  match($0, $LISTNUMBER); print substr($0, RLENGTH + 2); }' /home/user/list)

echo "you chose $USERNAME."

This script will use awk to search another file that has a list of numbers and usernames: 1 bob 2 fred etc... I only want the username not the corresponding number which is why I tried using: print substr($0, RLENGTH + 2)

Unfortunately, the output of the awk won't attach to $USERNAME.

I have attempted to grep for this but could not achieve the answer. I then read about awk and got here, but am stuck again. Utilizing grep or awk is all the same for me.

Trevor
  • 1,111
  • 2
  • 18
  • 30
cole
  • 29
  • 4

1 Answers1

4

Single-quoted strings in POSIX-like shells are invariably literals - no interpolation of their contents is performed. Therefore, $LISTNUMBER in your code will not expand to its value.

To pass shell variables to Awk, use -v {awkVarName}="${shellVarName}".

Also, Awk performs automatic splitting of input lines into fields of by runs of whitespace (by default); $1 represents the 1st field, $2 the 2nd, ...

If we apply both insights to your scenario, we get:

#!/bin/bash

read -p "enter a number: " LISTNUMBER
USERNAME=$(awk -v LISTNUMBER="$LISTNUMBER" '
  $1 == LISTNUMBER { print $2 }' /home/user/list)

echo "you chose $USERNAME."
mklement0
  • 382,024
  • 64
  • 607
  • 775