最大3つのスペースを入力してください(\ sを含む)。

最大3つのスペースを入力してください(\ sを含む)。

次のチュートリアルによると

  1. https://linuxize.com/post/regular-expressions-in-grep/

\s はスペースと一致します。

そして

  1. https://www.guru99.com/linux-regular-expressions.html

いくつかの間隔正規表現は次のとおりです。

表現の説​​明

{n} は前の文字 "n" 番と正確に一致します。

{n,m} は前の文字 'n' 番と一致しますが、m 以下です。

{n、}先行文字が「n」回以上表示される場合にのみ、その文字と一致します。

サンプルファイル

wolf@linux:~$ cat space.txt
0space
1 spaces
2  spaces
3   spaces
4    spaces
wolf@linux:~$ 

最大3つのスペース、少なくとも1つのスペース、最大3つのスペースをgrepしたいと思います。残念ながら、予想通り実際には動作しません。

wolf@linux:~$ cat space.txt | grep -P '\s{1,3}'
1 spaces
2  spaces
3   spaces
4    spaces
wolf@linux:~$ 

wolf@linux:~$ cat space.txt | grep -P '\s{3}'
3   spaces
4    spaces
wolf@linux:~$ 

wolf@linux:~$ cat space.txt | grep -P '\s{3,3}'
3   spaces
4    spaces
wolf@linux:~$ 

wolf@linux:~$ cat space.txt | grep -P '\s{0,3}'
0space
1 spaces
2  spaces
3   spaces
4    spaces
wolf@linux:~$ 

希望の出力

wolf@linux:~$ cat space.txt | grep -P '\s{0,3}' <- need to fix it here
1 spaces
2  spaces
3   spaces
wolf@linux:~$ 

ベストアンサー1

以下を行う必要があります。

grep -P '\S\s{1,3}\S' infile

\s空白文字と一致します。だけでなくスペース。
\S空白以外の文字と一致

あなたの試みは、試合の前後にスペースを入れないように制限しません。


空白のみをフィルタリングして PCRE を防止するには、次のようにします。

grep '[^ ] \{1,3\}[^ ]' infile

または、先行/末尾の1〜3個のスペースがある行で作業します。

grep '\([^ ]\|^\) \{1,3\}\([^ ]\|$\)' infile

https://regexper.com/で検索

入力データ(cat -e infile):

0space$
1 spaces$
2  spaces$
3   spaces$
4    spaces$
   3spaces$
    4space$
3spaces   $
4spaces    $

出力:

1 spaces$
2  spaces$
3   spaces$
   3spaces$
3spaces   $

おすすめ記事