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.

3
  • use awk -v variable... : stackoverflow.com/questions/15786777/… Commented Dec 13, 2015 at 2:01
  • 1
    my apologies if this is a re-ask. thanks for the link. Commented Dec 13, 2015 at 2:30
  • No thing wrong with asking same question again.. :) Commented Dec 13, 2015 at 2:38

1 Answer 1

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."
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.