How to pass different values including a space separated string stored in a variable to grep command - bash

I have a string stored in a variable like
errors="ORA-01000:|ORA-03113:|ORA-01555|ORA-19815:|shutdown|ORA-27603"
That works fine when I pass it to the grep command like
more filename.txt |grep -E $errors | awk '{print $1 $2}' >> temp.txt
But as soon as I include a string e.g "table found" in this "errors" variable like this
errors="ORA-01000:|ORA-03113:|ORA-01555|ORA-19815:|shutdown|ORA-27603|table found"
The above mentioned grep command does not work and gives the error
grep: **found**: No such file or directory
I am sort of stuck dealing with it when space separated option is passed as an "OR" option to $error

Just enclose your variable with double quotes
more filename.txt | grep -E "$errors"
If you had, say
errors="2:|a-3|table found"
the command
more filename.txt | grep -E $errors
would be like running
more filename.txt | grep -E "2:|a-3|table" found
since the shell replaces $errors with its value 2:|a-3|table found and then again splits the line into words, which would be (for the grep command only):
grep
-E
2:|a-3|table
found
therefore executing grep with the option -E, the pattern 2:|a-3|table and the file found. The content of filename.txt which is additionally piped into that command is ignored.

Related

User input into variables and grep a file for pattern

H!
So I am trying to run a script which looks for a string pattern.
For example, from a file I want to find 2 words, located separately
"I like toast, toast is amazing. Bread is just toast before it was toasted."
I want to invoke it from the command line using something like this:
./myscript.sh myfile.txt "toast bread"
My code so far:
text_file=$1
keyword_first=$2
keyword_second=$3
find_keyword=$(cat $text_file | grep -w "$keyword_first""$keyword_second" )
echo $find_keyword
i have tried a few different ways. Directly from the command line I can make it run using:
cat myfile.txt | grep -E 'toast|bread'
I'm trying to put the user input into variables and use the variables to grep the file
You seem to be looking simply for
grep -E "$2|$3" "$1"
What works on the command line will also work in a script, though you will need to switch to double quotes for the shell to replace variables inside the quotes.
In this case, the -E option can be replaced with multiple -e options, too.
grep -e "$2" -e "$3" "$1"
You can pipe to grep twice:
find_keyword=$(cat $text_file | grep -w "$keyword_first" | grep -w "$keyword_second")
Note that your search word "bread" is not found because the string contains the uppercase "Bread". If you want to find the words regardless of this, you should use the case-insensitive option -i for grep:
find_keyword=$(cat $text_file | grep -w -i "$keyword_first" | grep -w -i "$keyword_second")
In a full script:
#!/bin/bash
#
# usage: ./myscript.sh myfile.txt "toast" "bread"
text_file=$1
keyword_first=$2
keyword_second=$3
find_keyword=$(cat $text_file | grep -w -i "$keyword_first" | grep -w -i "$keyword_second")
echo $find_keyword

grep for exact word in a file containing "."

I have a file named "TestGrep" that contains content as shown below
#!/bin/bash
/ParentFolder/a #email1.com
/ParentFolder/b #email2.com
/ParentFolder/.a #email1.com
/ParentFolder/.b #email2.com
/ParentFolder/ #email3.com
I am using the below grep command
grep -Fw "/ParentFolder/" TestGrep
The output is
/ParentFolder/.a #email1.com
/ParentFolder/.b #email2.com
/ParentFolder/ #email3.com
It is somehow ignoring the dots in the TestGrep file.
I want the output to be shown as below
/ParentFolder/ #email3.com
How can I query using grep command that would just check if the exact string match is done and return output as expected.
Could you please try following. Using -E option of grep here.
grep -E '/ParentFolder/\s+' Input_file
From man grep about -E option of grep:
-E, --extended-regexp
Interpret PATTERN as an extended regular expression
\s+ means looks for spaces one or more occurrences.

Edit (sed) specific line in a file where a string occurs

I have a folder full of textfiles which i want to grep for a specific String, then add a String (let's say a "+ ") via sed at the beginning of that specific line (at all places where the search-String occurs).
So far i got this:
if grep -q &MyString /path/to/folder/* ; then
echo "String detected"
sed 's/^/+ /g' -i [what to put in here?]
fi
depending on what i put in the brackets it either adds the String in front of every line of every textfile or does nothing because i dont define a correct file. How would i reference the file i detected the String in before?
Thanks
grep -l &MyString /path/to/folder/* | uniq | while read line
do
echo "String detected"
sed '/&MyString/ s/^/+ /g' -i $line
done
Using grep with -l to print just the filename, use uniq to deduplicate and then read each line of the output. Taking each line from the output, use this to represent the filename in sed ($line).
Read line is used as opposed for var in $(grep ...) as this would cause issues for files with spaces in them as each space delimited variable in the output would be used to represent the filename.

Storing multiple grep parameters in a bash variable

I want to store multiple grep parameters in a bash variable, so I can define the parameters in the configuration section at the top of my file, and use it in multiple locations.
How do I need to define the variable and write the grep command?
Details
My first attempt
# CONFIG: grep parameters to further filter ...
GREP_PARAM="-E .*"
# ...
grep "^Stop " $1 | grep $GREP_PARAM | sed "..." >>$TFILE
results in
grep: ..: Is a directory
Using .\* or .\\* instead causes grep to not match anything, instead of everything.
Using grep "$GREP_PARAM" instead only works if GREP_PARAM contains a single parameter, but not otherwise; e.g. if it contains -v .*SAT.* or -v .\*SAT.\* or -v .\\*SAT.\\*, I get
grep: invalid option --
This is exactly what arrays were introduced to handle.
grep_options=(-E '.*')
grep "^Stop " "$1" | grep "${grep_options[#]}" | sed "..." >> "$TFILE"

grepping string from long text

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.
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
You can use sed as
cat results.txt | sed -n 's/.*isDisabled=\(.\).*/\1/p'
This will print the value of isDisbaled.

Resources