我有多个文件,其数据类似于以下示例:
[[Public IP Addresses ]]
// Here, IP addresses will
IPv6 display format.
[LINK_7]
linkNum=7.
在这里,我必须提取"公共IP地址" .i.e双方括号内的任何内容。即我想要一个sed / awk / grep等脚本来提取双方括号内的任何内容 我徒劳地尝试了很多选择。对此有一些帮助表示赞赏。
答案 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