简体   繁体   中英

Count the number of occurrences of a string with a variable substring in a file in bash

I want to count the number of occurrences of a string Exiting with return code $var in a text file dump.out where 0<$var<29 .

ie I only want to consider the strings where $var is any value between 0 and 29 including both the limits.

I want to check it like this:

if [ $(grep -c "Exiting with return code 0" dump.out) -ne 5 ]; then
  rc=1
  exit 0
fi

But here only string with 0 s are considered.

Any suggestions will be helpful!

For 0 <= $var <= 29

grep -c 'Exiting with return code \([0-9]\|[12][0-9]\)'

For 0 < $var < 29

grep -c 'Exiting with return code \([1-9]\|1[0-9]\|2[0-8]\)'

Note that it can match 134, as it start with 1 , so you might need to specify the following character (or $ if there's none).

You can try this:

grep -c -E 'Exiting with return code [12]?[0-9]([^0-9]|$)' dump.out

-E let grep use the extended regex (ERE)
[12]?[0-9] is matching numbers 0,1,...,29
([^0-9]|$) matches the end of the line or anything except a digit

试试这个可能会有所帮助

grep -w -c "Exiting with return code [012][0-9]\|Exiting with return code [0-9]" dump.out

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