Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

utilizing a variable in awk then enter output into another variable

Tags:

bash

shell

awk

#!/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.

like image 214
cole Avatar asked Aug 16 '26 23:08

cole


1 Answers

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."
like image 75
mklement0 Avatar answered Aug 18 '26 19:08

mklement0



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!