Reputation: 29
#!/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.
Upvotes: 3
Views: 152
Reputation: 437803
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."
Upvotes: 4