Results 1 to 4 of 4
Nice - forum, first time user but hope to be more regular now.
So, yes, this is a homework question, but no - I'm not trying to get anyone to ...
- 04-04-2010 #1Just Joined!
- Join Date
- Apr 2010
- Posts
- 2
gawk - using variable in search pattern
Nice - forum, first time user but hope to be more regular now.
So, yes, this is a homework question, but no - I'm not trying to get anyone to do it for me. I think that I am really close, but can't quite get one small aspect to work.
in gawk, I want to include a variable name in the search string, but the below code doesn't work.
This, does, however:read -p 'Login name please? ' uLogName
userID=$(gawk -F: '/"$uLogName"/{print $3}' /etc/passwd)
echo $userID
I've explored the -v option, but have had no luck. I've Googled myself blue in the face looking for a usable example.Code:read -p 'Login name please? ' uLogName userID=$(gawk -F: '/stevej/{print $3}' /etc/passwd) echo $userID
Thanks,
- 04-05-2010 #2
Assuming you are doing this with Bash, it could be that your version of bash does not grok the $( command ) syntax. Try backticks instead:
--- rod.Code:userID=`gawk -F: '/stevej/{print $3}' /etc/passwd`Stuff happens. Then stays happened.
- 04-05-2010 #3Just Joined!
- Join Date
- Apr 2010
- Posts
- 2
Thank you for the prompt reply; I may not have written my question clearly enough, though.
The one that works is
The one that doesn't work isCode:userID=$(gawk -F: '/stevej/{print $3}' /etc/passwd)
If I use the code example that you gave me, but put in the variable name instead,it continues not to work.Code:userID=$(gawk -F: '/"$uLogName"/{print $3}' /etc/passwd)
Code:userID=`gawk -F: '/"$userID"/{print $3}' /etc/passwd`
So my question still remains as to how to substitute a variable in gawk.
Incidentally, I finally went with the solution below. It works, so I was able to move on. I still would like to understand gawk better for the future.
Thanks again,Code:read -p 'Login name please? ' uLogName userID=$(grep "$uLogName" /etc/passwd | gawk -F: '{print $3}') if (( ${#userID} != 0)) then echo; echo "According to /etc/passwd," echo "Your userID is: $userID" else echo "The userID was not found" exit 1 fi
SteveJ
- 04-05-2010 #4
The shell variable in your original example was enclosed in single quotes, preventing it from being interpolated. Once it released from those quotes, it can be interpolated, rather than taking its value as the literal string '$uLogName'.
--- rod.Stuff happens. Then stays happened.


Reply With Quote