![如何从以单括号开头和以单括号结尾的文件行中捕获](https://linux22.com/image/12383/%E5%A6%82%E4%BD%95%E4%BB%8E%E4%BB%A5%E5%8D%95%E6%8B%AC%E5%8F%B7%E5%BC%80%E5%A4%B4%E5%92%8C%E4%BB%A5%E5%8D%95%E6%8B%AC%E5%8F%B7%E7%BB%93%E5%B0%BE%E7%9A%84%E6%96%87%E4%BB%B6%E8%A1%8C%E4%B8%AD%E6%8D%95%E8%8E%B7.png)
如何从以单括号开头和以单括号结尾的文件行中捕获
我试试这个
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 file
1)之前不需要grep
2) 使用更准确的正则表达式模式[[^]]\+\]$
$ grep '\[[^]]\+\]$' file
[1006, 1005, 1004, 1003, 1002, 1001]