Reputation: 133
How do I get the following awk script to pass the username result of whoami
to get stored in a variable and then called upon to search for that text with awk. I seem to be able to pass $myCount but not $myUser
myUser=$(whoami)
myCount=6
awk -v count=$myCount -v Bob=$myUser '/"tg-6k2t".*Bob/{x=count}x--==1{sub(/tg-6k2t/,"tg-b5xm")}1' file
Upvotes: 0
Views: 192
Reputation: 203209
Passing the value isn't your problem, trying to reference it inside a constant regexp is. Set -v user="$myUser"
on the command line list like you're setting count
and change:
/"tg-6k2t".*Bob/
to:
$0 ~ ("\"tg-6k2t\".*" user)
The parens aren't strictly necessary, just there to improve readability. You need to add $0 ~
because the regexp literal /foo/
on it's own in a conditional context is shorthand for $0 ~ /foo/
but "foo"
in a conditional context is just a test to see if a string is not null and you need to make it explicitly $0 ~ "foo"
to make it a regexp comparison of $0 against a dynamic regexp.
You might want to consider making your whole script parameterized:
awk -v count="$myCount" -v user="$myUser" -v old='tg-6k2t' -v new='tg-b5xm' '
$0 ~ ("\"" old "\".*" user){x=count} x--==1{sub(old,new)} 1
' file
Upvotes: 2