Posted on 09-13-2019 08:09 PM
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
Posted on 09-14-2019 01:02 PM
Try this for the awk command:
awk -v var="$loggedInUser" -F',' '$0 ~ var {print $2}' /path/to/file
Posted on 09-15-2019 08:35 PM
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