BEGIN
{
i=0; # declaring variable
}
{
if (NF==2){currgrp=$1;} # check whether awk actually processing 2 column record, if yes save the group name
else
{
if ($1~/uname/) # else if awk is processing 1 column record and is found user name, save the group name to array and increment i
{
netgroups=currgrp;
i++;
}
}
}
END # at the end of processing whole file print the array (all saved groups)
{
for(j=0;j<i;j++)
{
print netgroups;
}
}
$ u=user1
$ sed -n '/^group/h; /'"$u"'/{g;s/[[:blank:]].*$//;p;}' file
group1
group2
I would recommend against using this type of solution unless you can guarantee that the user name will not contain any sed regular expression special characters ("/", ".", "*", "\" .. come immediately to mind).
BEGIN { # do not put BEGIN on a line by itself
i = 0 # no need to initialize the counter,
# awk does this automatically
}
{
if (NF == 2) {
currgrp = $1
if ($2 ~ uname) {
netgroups = currgrp # you shoud check if the username matches
i ++ # when NF == 2 too
}
}
else
{
if ($1 ~ uname) { # /uname/ matches litteral "uname"
netgroups = currgrp
i ++
}
}
}
END { # do not put END on a line by itself
for(j = 0; j < i;j ++)
{
print netgroups[j] # j not i!
}
}
There's nothing wrong with those two lines. BEGIN and END are syntactically no different from any other pattern. So long as the corresponding action begins on the same line (the opening curly brace is sufficient), it's fine.
Example:
$ cat beginend.awk
BEGIN {
print "begin"
}
END {
print "end"
}
$ echo | awk -f beginend.awk
begin
end
---------- Post updated at 10:04 PM ---------- Previous update was at 10:01 PM ----------
Good point,
I suppose the OP meant == not ~ .
---------- Post updated at 10:21 PM ---------- Previous update was at 10:04 PM ----------
Just to add that the special patterns BEGIN and END are actually syntactically different from the regular patterns because they require an action part.