According to the following tutorials
\s Match a space.
and
Some interval regular expressions are:
Expression Description
{n} Matches the preceding character appearing 'n' times exactly
{n,m} Matches the preceding character appearing 'n' times but not more than m
{n, } Matches the preceding character only when it appears 'n'
times or more
Sample file
wolf@linux:~$ cat space.txt
0space
1 spaces
2 spaces
3 spaces
4 spaces
wolf@linux:~$
I just want to grep up to 3 spaces only, minimum 1 space, maximum 3 spaces
Unfortunately, it doesn't really work as expected.
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:~$
Desired Output
wolf@linux:~$ cat space.txt | grep -P '\s{0,3}' <- need to fix it here
1 spaces
2 spaces
3 spaces
wolf@linux:~$
Best Answer
you need:
\s
matches a whitespace-character, not only a space.\S
matches a non-whitespace-characterin your attempt, you are not limiting that before &after your matches should not be a whitespace.
to filter on space only and avoid using PCRE, you can do:
or to work on lines having leading/trailing 1~3spaces:
input data (
cat -e infile
):output: