2

正規表現で一致する特定の文字のすべての位置を取得しようとしています。expr インデックスでこれを行うことができますが、これは文字列の最初の文字のみに一致します。

echo $(expr index "$z" '[\x1F\x7F-\x9F]') 

注: $z は文字列を含む変数です

これは(正しく)次を返します。

6

この文字列には、6 と 12 の位置に 2 つの一致する文字があり、最初の文字だけでなく、一致した文字のすべての位置を返したいことがわかっています。

手伝って頂けますか?ありがとうございました!

4

2 に答える 2

2

awk を使用したコマンドを次に示します。正規表現に一致するすべての位置を出力します/0-9/

echo $z | awk  '{s=$0; i=1; idx=0; 
       while(i>0){ 
           i=match(s, /[0-9]/); 
           if(i>0) {
                  idx += i;
                  print idx; 
                  s=substr(s, i+1);
           }
       }
}'
于 2013-04-24T13:37:39.387 に答える
0

を使用することをお勧めしgrepます。

#!/bin/bash

matches=();

# Used a "Process Substitution" because of the loop's subshell
while read match
do
    matches+=( "$match" );
done \
< <(
    printf '%s\n%s' \
        'somedata{a917am}some{8ka81a}data' \
        'awd123{ad123d}adad' \
        | grep -Eobn '\{[0-9a-z]{6}\}' # The magic is here
);

for (( i = 0; i < ${#matches[@]}; i++ ));
do
    matchRaw="${matches[$i]}";
    match="${matchRaw#*\:}";
    match="${match#*\:}";
    matchLine="${matchRaw%%\:*}";
    matchChar="${matchRaw#*\:}";
    matchChar="${matchChar%%\:*}";
    matchLength="${#match}";

    printf 'Match #%s, line %2s, char %2s, length %2s: "%s"\n' \
        "$((i + 1))" \
        "$matchLine" \
        "$matchChar" \
        "$matchLength" \
        "$match";
done

出力:

Match #1, line  1, char  8, length  8: "{a917am}"
Match #2, line  1, char 20, length  8: "{8ka81a}"
Match #3, line  2, char 39, length  8: "{ad123d}"

で動作しgrep (GNU grep) 2.25ます。

関連している:

grep --help

# -E, --extended-regexp     PATTERN is an extended regular expression (ERE)
# -o, --only-matching       show only the part of a line matching PATTERN
# -b, --byte-offset         print the byte offset with output lines
# -n, --line-number         print line number with output lines

プロセス代替(から)

于 2021-06-06T09:24:44.847 に答える