1

I have a list of commands to parse through for an audit, similar to this:

1. -a *policy name=PolicyName -a *policy workflow name=PolicyWorkflow -a *policy action name=PolicyAction -s Server -b Storage -J Node -y 1 Months -o -F -S
2. -a *policy name=PolicyName -a *policy workflow name=PolicyWorkflow -a *policy action name=PolicyAction -s Server -b Storage -J Node -y 1 Months -o -F -S
3. -a *policy name=Policy Name -a *policy workflow name=PolicyWorkflow -a *policy action name=PolicyAction -s Server -b Storage -J Node -y 1 Months -o -F -S

I'm trying to set each of the name=Value to variables. As this is a standard pattern, i used read with success, however when I get to a line with whitespace (see line 3), it offsets all my variables. I'm unsure how to tackle this without looping through each word in the line and matching specific patterns. Hoping someone would have a better solution out there.

  • You could just use sed to replace all instances of 'Policy Name' with PolicyName prior to using read, e.g. sed 's/Policy Name/PolicyName/g' <Input_file> | while read ... – Warwick May 26 '18 at 5:30
  • @Warwick Only if the whitespace is unimportant and the policy name is actually "Policy Name" and not just a placeholder for an actual policy name that the poster inserted to show the general pattern. – Kusalananda May 26 '18 at 6:40
0

In bash and using an array variable instead, you can do something like:

{ IFS=$'\n'; array=($(grep -Po 'name=[^-]+(?=\s*-)' infile)); }

then print the elements of the array (array Index in bash starts from 0):

printf '%s\n' "${array[@]}"
name=PolicyName
name=PolicyWorkflow
name=PolicyAction
name=PolicyName
name=PolicyWorkflow
name=PolicyAction
name=Policy Name
name=PolicyWorkflow
name=PolicyAction

Or to print just a single element:

printf '%s\n' "${array[6]}"
name=Policy Name
  • We defined IFS to "\newline" character IFS=$'\n' so that the word splitting will happen on "\newline" character only on the result of unquotedCommand Substitution $(...).

  • The syntax { list; } is known Grouping Commands and I just used to grouping my commands.

  • The array=(...) syntax is used to creating an associated array variable named array.

  • With grep -Po 'name=[^-]+(?=\s*-)' infile, we print -only the matches that matches the pattern "name=" followed by any non-zero length of characters but a hyphen [^-]+ which follows by zero-or-more whitespaces until a hyphen (?=\s*-).


Future reading:

  • This is exactly what i was looking for, thank you. – Justin Davis May 26 '18 at 12:40
  • @JustinDavis I added some explanations if you were interested to know what is happening. – αғsнιη May 28 '18 at 11:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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