如何从以单括号开头和以单括号结尾的文件行中捕获

如何从以单括号开头和以单括号结尾的文件行中捕获

如何从以单括号开头和以单括号结尾的文件行中捕获

我试试这个

cat file  | grep "\[*\]"

但不确定这种语法是否能给出好的结果

文件示例:

cat file

WATCHER::
[1006, 1005, 1004, 1003, 1002, 1001]
Welcome to ZooKeeper!
JLine support is disabled

WATCHER::

WatchedEvent state:SyncConnected type:None path:null

预期产出

[1006, 1005, 1004, 1003, 1002, 1001]

答案1

grep '^\[.*\]$' file
  • ^匹配行的开头
  • \[匹配左括号
  • .*匹配任意字符、任意数量(零个或多个)
  • \]匹配右括号
  • $匹配行尾

答案2

具有更复杂输入数据的源文件:

$ cat file2
WATCHER::
[1006, 1005, 1004, 1003, 1002, 1001]
Welcome to ZooKeeper!
JLine support is disabled

WATCHER::

WatchedEvent state:SyncConnected type:None path:null
begin [20, 25, 24, 23, 22, 21] end
begin2 [30, 35, 34, 33,
 32, 31] end2
begin3 [40, 41] middle3 [50, 51, 52] end3
end of file
$

1. 简单

$ grep '\[[^]]*\]' file2
[1006, 1005, 1004, 1003, 1002, 1001]
begin [20, 25, 24, 23, 22, 21] end
begin3 [40, 41] middle3 [50, 51, 52] end3
$

2. 高级

$ cat file2|grep '\[[^[]*\]'|sed 's/^[^[]*\[/[/g;s/][^]]*$/]/g;s/][^[]*\[/] [/g'
[1006, 1005, 1004, 1003, 1002, 1001]
[20, 25, 24, 23, 22, 21]
[40, 41] [50, 51, 52]
$

3. 高级多线

$ sed ':a;N;$!ba;s/^[^[]*\[/[/g;s/][^]]*$/]/g;s/\n//g;s/][^[]*\[/]\n[/g;' file2
[1006, 1005, 1004, 1003, 1002, 1001]
[20, 25, 24, 23, 22, 21]
[30, 35, 34, 33, 32, 31]
[40, 41]
[50, 51, 52]
$

答案3

cat file1)之前不需要grep
2) 使用更准确的正则表达式模式[[^]]\+\]$

$ grep '\[[^]]\+\]$' file
[1006, 1005, 1004, 1003, 1002, 1001]

相关内容