简体   繁体   中英

How can I grep 2 occurrences of string “ATAT” out of string “ATATAT”. I only get one

I am trying to write a command to grep the number of occurrences in a string, but my string is "ATATAT" and I want to grep "ATAT". I am expecting to get 2 outputs when I use command I get only 1.

echo "ATATAT" |grep -o "ATAT" 

I have tried surrounding the string with ** but still it only matches one pattern.

The simplest way - make Python do it for you:

python -c "import re; print(re.findall(r'(?=(ATAT))', 'ATATAT'))"
['ATAT', 'ATAT']

The long way with bash:

string="ATATAT"
regex="ATAT"
length="${#string}"
counter=0

for((i=0;i<$length;i++)); do
  [[ "${string:$i}" =~ ^$regex ]] && ((counter++))
done

echo "$counter"

Output:

2

Inspired by the Python answer, here's a solution using ripgrep

$ echo 'ATATAT' | rg -oP '(?=(ATAT))' -r '$1'
ATAT
ATAT
$ echo 'ATATXAT' | rg -oP '(?=(ATAT))' -r '$1'
ATAT
$ echo 'ATATATATAT' | rg -oP '(?=(ATAT))' -r '$1'
ATAT
ATAT
ATAT
ATAT

(?=(ATAT)) is a positive lookahead (see also What does this regex mean? ), it will check a condition without consuming characters and thus possible to do overlapping matches. -r option allows to replace the matching portion with something else.

Or, use perl

$ # the if condition is there to prevent empty lines for non-matching input lines
$ echo 'ATATATATAT' | perl -lne 'print join "\n", //g if /(?=(ATAT))/'
ATAT
ATAT
ATAT
ATAT


If you just need the count:

$ echo 'ATATATATAT' | rg -coP '(?=(ATAT))'
4
$ # with GNU grep, if PCRE is available
$ echo 'ATATATATAT' | grep -oP 'AT(?=(AT))' | wc -l
4

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