Bash script HELP

jandrews1964
New Contributor

hi, New to scripting..

I have a .txt file with something similar to this..

jstreet, aliasjstreet
jSimpson, aliasjsimpson
blong, aliasblong

So, My script searches for the logged in user (e.g jSimpson)

I want to extract the text after the comma only for the specific search.

How do I do this??

The script, at present finds the user but selects all in the second column.
Hope this makes sense?

#!/bin/sh
loggedInUser=$(/bin/ls -l /dev/console | /usr/bin/awk '{ print $3 }')

name=$(awk -F',' '{ if ($1 =='$loggedInUser')} { print $2 } ' “path to text file”)

echo $name

Thanks for the assistance

2 REPLIES 2

mikeh
Contributor II

Try this for the awk command:

awk -v var="$loggedInUser" -F',' '$0 ~ var {print $2}' /path/to/file

tlarkin
Honored Contributor

been a minute where I used awk heavily, but if you escape out to the shell with pattern matching this does work in my limited testing

echo "foo,bar" > /tmp/test
whoami
tlarkin
echo "tlarkin,foobar" >> /tmp/test 
echo "test,test2" >> /tmp/test
currentuser=$(scutil <<< "show State:/Users/ConsoleUser" | awk '/Name :/ && ! /loginwindow/ { print $3 }')
awk -F, '/^'"${currentuser}"'/ { print $2 }' /tmp/test 
foobar
cat /tmp/test 
foo,bar
tlarkin,foobar
test,test2

It is an old trick I have used when parsing CSV file with awk, although I would say there are CSV parsing tools out there that might do this better, but awk is also fine to use