使用正则表达式查找行号

1 sed

我试图使用unix sed命令来查找与特定正则表达式匹配的行号.我的文件模式如下

A<20 spaces>
<something>
<something>
..
..
A<20 spaces>
<soemthing>
<something>
Run Code Online (Sandbox Code Playgroud)

我需要所有的行号 A<20 spaces>

我使用sed -n '/A[ ]{20}/'= <file_name>但它不起作用.如果我手动键入二十个空格,它确实有用.

有人可以调整上面的命令使它工作.

Joh*_*web 5

表达式中的大括号需要使用反斜杠进行转义:

% sed -n '/A[ ]\{20\}/=' test.txt
1
6
Run Code Online (Sandbox Code Playgroud)

另一种方法是使用-E将正则表达式解释为扩展(现代)正则表达式:

% sed -nE '/A[ ]{20}/=' test.txt 
1
6
Run Code Online (Sandbox Code Playgroud)

或者可能使用grep,这需要更少的字符来指定相同的搜索:

% grep -n 'A[ ]\{20\}' test.txt 
Run Code Online (Sandbox Code Playgroud)