I have been trying to write a script with awk to print the name of a users rolegroup(s), if the username matches an input variable.

The input file is similar to the following


As you can see, the file is separated by sssss. I know that the name I am looking for is trevor and I want the script to print the value activedir. The fields aren't always in the same order (there are multiple fields, this just being an example).

I tried the following...

USERNAME=`cat trevor.txt`
awk 'BEGIN {RS="sssss"; FS="\n";} if username=$USERNAME then {awk '/xxrolegroups/ {getline; print }}'

Please excuse the pseudo-code, just trying to convey what I'm trying to do :-)


closed as unclear what you're asking by αғsнιη, Jesse_b, Kiwy, vonbrand, G-Man May 4 '18 at 21:11

Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.

  • 1
    Hello and welcome to U&L. Please add an example of the desired output to your question. – roaima May 3 '18 at 15:15
  • Also, please differentiate whether your input file is the trevor.txt from your example, and if not, what trevor.txt contains. (my assumption is it simply contains trevor, if I understand your question) – cunninghamp3 May 3 '18 at 15:39
  • 1
    Should the script print activedir when it's found trevor, or only if it finds this keyword in trevor's block? Should it print anything if it cannot find activedir in the block containing trevor? – roaima May 3 '18 at 16:17
  • I'd use a more capable language for such a task, like Python or Perl. – vonbrand May 4 '18 at 13:55

You can use a script like this. I've split it up to help with readability, but you can literally concatenate all the lines if you prefer:

awk -v key=trevor '
    BEGIN { RS="^sssss$"; RE="\n" key "\n" }
    $0 ~ RE && /activedir/ { print "activedir" }
' datafile.txt

It sets the record separator to a line consisting of sssss and creates a Regular Expression that matches the key trevor to a full line within that record. Then, if it can match the RE and it finds activedir it prints the required text.

Not the answer you're looking for? Browse other questions tagged or ask your own question.