0

I created my basic variable from a read command (I've done this manually and using a script):

read NAME

I then want to use that NAME variable to search a file and create another variable:

STUDENT=$(grep $NAME <students.dat | awk -F: '/$NAME/ {print $1}')

If I run the command manually with an actual name from that students.dat file (and not $NAME), it executes and displays what I want. However, when I run this command (manually or from the script using $NAME), it returns blank, and I'm not sure why.

2 Answers 2

2

@user1615415: Try:

cat script.ksh
echo "Enter name.."
read NAME
STUDENT=$(awk -vname="$NAME" -F: '($0 ~ name){print $3}' student.dat)
Sign up to request clarification or add additional context in comments.

Comments

1

Shell variables aren't interpolated in single quotes, only double quotes.

STUDENT=$(grep $NAME <students.dat | awk -F: "/$NAME/ {print \$1}")

$1 needs to be escaped to ensure it's not expanded by the shell, but by awk.

3 Comments

Passing the value of $NAME with the -v option is safer.
Beautiful! That did it. Thanks!
It's better to enclose $NAME in double quotes while passing to grep. Also, use -- to prevent failures caused by any leading - in $NAME. So, grep -- "$NAME" is much better.

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.