简体   繁体   中英

Searching a string in shell script

I am trying to learn shell script. So sorry if my question is so simple.

I am having a file called one.txt and if either strings 1.2 or 1.3 is present in the string then I have to display the success message else the failure message.

The code I tried is follows,

#!/bin/bash
echo "checking"
if grep -q 1.2 /root/one | grep -q 1.3 /root/one; then
echo " vetri Your NAC version"
fi

What I am doing wrong here ?

You have to use ||

#!/bin/bash
echo "checking"
if grep -q 1.2 /root/one || grep -q 1.3 /root/one; then
echo " vetri Your NAC version"
fi

Single | operator is called pipe. It will pass the output of the command before | to the command after | .

You can also include the OR in your grep pattern like so:

grep '1.2\|1.3' /root/one

details here

Update: as twalberg pointed out in the comment, my answer was not precise enough. The better pattern is:

grep '1\.2\|1\.3' /root/one

Or even better, because more compact:

grep '1\.[23]' /root/one

It is better to join these these greps with | (OR operator):

grep '1.2\|1.3'

or

grep -E '1.2|1.3'

I guess the easier way to do this is to create a variable to check the count of occurrences:

#!/bin/bash
echo "checking"
CHECK=`egrep -c '1\.(2|3)' /root/one`
if [ "$CHECK" -gt 0 ]; then
  echo "vetri Your NAC version"
fi

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM