如何提取字符串中$(...)内的子串?awk脚本问题排查
问题排查与解决
问题背景
我在Quora上查过模式提取子串的相关内容,但没法在自己的场景里实现成功。现有如下格式的字符串:
https://$(test.url)/bbmap-oautsdsdh-prdswdovdsdsdider/oausdsdth2/tokedsdsdn $(test2.url)/b123bmap-oautsd212sdh-prdswd343ovdsdsdider/oausdsdth2/tokedsdsdn https://$(test3.url)/bbmap-oautdsdsdsdh-prdswdosdvdsdsdider/oausdsdtsdh2/sd
需要提取出:
test.url test2.url test3.url
尝试了下面的脚本,但没得到预期结果:
my_var='https://$(test.url)/bbmap-oautsdsdh-prdswdovdsdsdider/oausdsdth2/tokedsdsdn' echo $my_var | awk -F[\(\)] '{print $2}'
预期输出:
test.url
问题原因
你的awk字段分隔符写法有误:-F[\(\)]没加引号,shell会把未转义的括号当作特殊字符解析,导致awk实际接收到的分隔符参数不正确,没法正确分割字符串。另外,echo $my_var没有用引号包裹,变量中的特殊字符可能被shell意外展开,破坏原字符串结构。
修复方案
单条字符串处理
给awk的分隔符加上单引号,避免shell解析,同时用双引号包裹$my_var保留原格式:
my_var='https://$(test.url)/bbmap-oautsdsdh-prdswdovdsdsdider/oausdsdth2/tokedsdsdn' echo "$my_var" | awk -F'[()]' '{print $2}'
执行后就能输出test.url。
多行批量处理
如果要一次性处理所有目标字符串,直接用awk过滤匹配$(的行并提取:
awk -F'[()]' '/\$\(/ {print $2}' <<EOF https://$(test.url)/bbmap-oautsdsdh-prdswdovdsdsdider/oausdsdth2/tokedsdsdn $(test2.url)/b123bmap-oautsd212sdh-prdswd343ovdsdsdider/oausdsdth2/tokedsdsdn https://$(test3.url)/bbmap-oautdsdsdsdh-prdswdosdvdsdsdider/oausdsdtsdh2/sd EOF
运行后会输出所有预期的子串:
test.url test2.url test3.url
内容的提问来源于stack exchange,提问作者Dhaval Patel
相关产品推荐
相关产品推荐

