Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

grepping string from long text

Tags:

grep

bash

shell

The command below in OSX checks whether an account is disabled (or not).

I'd like to grep the string "isDisabled=X" to create a report of disabled users, but am not sure how to do this since the output is on three lines, and I'm interested in the first 12 characters of line three:

bash-3.2# pwpolicy -u jdoe -getpolicy
Getting policy for jdoe /LDAPv3/127.0.0.1

isDisabled=0 isAdminUser=1 newPasswordRequired=0 usingHistory=0 canModifyPasswordforSelf=1 usingExpirationDate=0 usingHardExpirationDate=0 requiresAlpha=0 requiresNumeric=0 expirationDateGMT=12/31/69 hardExpireDateGMT=12/31/69 maxMinutesUntilChangePassword=0 maxMinutesUntilDisabled=0 maxMinutesOfNonUse=0 maxFailedLoginAttempts=0 minChars=0 maxChars=0 passwordCannotBeName=0 validAfter=01/01/70 requiresMixedCase=0 requiresSymbol=0 notGuessablePattern=0 isSessionKeyAgent=0 isComputerAccount=0 adminClass=0 adminNoChangePasswords=0 adminNoSetPolicies=0 adminNoCreate=0 adminNoDelete=0 adminNoClearState=0 adminNoPromoteAdmins=0

Your ideas/suggestions are most appreciated! Ultimately this will be part of a Bash script. Thanks.

like image 665
Dan Avatar asked Jul 16 '26 03:07

Dan


1 Answers

This is how you would use grep to match "isDisabled=X":

grep -o "isDisabled=."


Explanation:
  • grep: invoke the grep command
  • -o: Use the --only-matching option for grep (From grep manual: "Print only the matched (non-empty) parts of a matching line, with each such part on a separate output line."
  • "isDisabled=.": This is the search pattern you give to grep. The . is part of the regular expression, it means "match any character except for newline".

Usage:

This is how you would use it as part of your script:

pwpolicy -u jdoe -getpolicy | grep -oE "isDisabled=."

This is how you can save the result to a variable:

status=$(pwpolicy -u jdoe -getpolicy | grep -oE "isDisabled=.")

If your command was run some time prior, and the results from the command was saved to a file called "results.txt", you use it as input to grep as follows:

grep -o "isDisabled=." results.txt
like image 146
sampson-chen Avatar answered Jul 19 '26 10:07

sampson-chen