0

I'm trying to get a string from a line from a file from user input.

It should output a name like this: Tharahan Muthu
from a string of letters like this: muthu:x:14232:504:Tharahan Muthu:/home/staff/muthu:/bin/bash
The name is always the 5th and 6th element.

It works fine, up to the awk line, after which it does not print anything.

#! /bin/bash

clear
echo "Type your n number"
read name
var1=$(grep -n $name /etc/passwd)
awk -v var="$var1" -F "[: ]" '/$0~var/{print $5" " $6 }' /etc/passwd

edit: fixed a typo where var="$var1" was typed var="$var2"

  • What exactly is your goal? Getting the full names from `/etc/passwd` records that match a user-supplied regular expression? – Shawn Oct 13 '18 at 01:21
  • 1
    Also see [How to use Shellcheck](http://github.com/koalaman/shellcheck), [How to debug a bash script?](http://unix.stackexchange.com/q/155551/56041) (U&L.SE), [How to debug a bash script?](http://stackoverflow.com/q/951336/608639) (SO), [How to debug bash script?](http://askubuntu.com/q/21136) (AskU), [Debugging Bash scripts](http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_02_03.html), etc. – jww Oct 13 '18 at 02:43
  • 1
    Possible duplicate of [How to match a pattern given in a variable in awk?](https://stackoverflow.com/questions/39384283/how-to-match-a-pattern-given-in-a-variable-in-awk) – Sundeep Oct 13 '18 at 06:59
  • 1
    You change from var1 to using $var2, which is undefined. You also ask for a number but seem to treat the input as a name. Then `grep -n` gives you a number which you treat as a regex. It's not clear what you're trying to do. – OpenSauce Oct 13 '18 at 08:33

2 Answers2

2

your awk pattern syntax is not right

awk -F: -v var="$var2" '$0~var{print $5}' /etc/passwd
karakfa
  • 66,216
  • 7
  • 41
  • 56
0

Thanks for all the quick answers!

I'll clarify the problem first, then go on to the solution.

The file /etc/passwd contains a list of a couple thousand people, with one person per line. On said line, there are multiple fields: their username, their full name, and an assortment of numbers all separated by colons. All fields are in the same position for each line(full name is always in the 5th)

I wanted to use grep to store the line that the username was on, then use awk to find the full name within that line.

I'm pretty new to bash, so I totally forgot about pipes and made it far too complicated for myself.


The Solution:

clear
echo "Please Enter Username:";<br>
read UNAME;<br>
grep $UNAME /etc/passwd | awk -F":" '{print "Full Name: " $5}'
exit 0