如何匹配双方括号内的字符串?

时间:2018-01-23 14:53:23

标签: regex bash shell awk sed

我有多个文件,其数据类似于以下示例:

 [[Public IP Addresses ]]  
// Here, IP addresses will   
 IPv6 display format.  
[LINK_7]  
linkNum=7.  

在这里,我必须提取"公共IP地址" .i.e双方括号内的任何内容。即我想要一个sed / awk / grep等脚本来提取双方括号内的任何内容  我徒劳地尝试了很多选择。对此有一些帮助表示赞赏。

3 个答案:

答案 0 :(得分:1)

您可能正在寻找

grep -oP '(?<=\[\[).*?(?=\]\])' file.txt

man grep

-P, --perl-regexp
       Interpret the pattern as a  Perl-compatible  regular  expression
       (PCRE).   This  is  highly  experimental and grep -P may warn of
       unimplemented features.
-o, --only-matching
       Print  only  the  matched  (non-empty) parts of a matching line,
       with each such part on a separate output line.

working example at regex101.com也会提供正则表达式的细分。

示例:

$ grep -oP '(?<=\[\[).*?(?=\]\])' <<EOF
[[Public IP Addresses ]]
// Here, IP addresses will
IPv6 display format.
[LINK_7]
linkNum=7.
EOF
Public IP Addresses

答案 1 :(得分:1)

只是为了好玩,这是一个纯粹的bash解决方案,假设输入文件为gash.txt

while read -r
do
    if [[ $REPLY == *'[['*']]'* ]]
    then
        extract=${REPLY/*'[['/}
        extract=${extract/']]'*/}
        echo "$extract"
    fi
done < gash.txt

答案 2 :(得分:0)

关注awk可能对您有帮助。

解决方案1:

awk '/\[\[/{match($0,/\[\[.*\]\]/);print substr($0,RSTART+2,RLENGTH-4)}'  Input_file

解决方案第二:

awk '/\[\[/{sub(/.*\[\[/,"");sub(/\]\].*/,"");print}'  Input_file

解决方案第3名: 使用sed来解决此问题。

sed -n '/\[\[/s/.*\[\[//;s/\]\].*//p'  Input_file