Regex 使用sed在开始和结束时删除一些字符
我正在尝试提取Regex 使用sed在开始和结束时删除一些字符,regex,awk,sed,grep,Regex,Awk,Sed,Grep,我正在尝试提取“profile”和“]”之间的单词 我的内容 [profile gateway] [profile personal] [profile DA] [profile CX] 为此我已经试过了 less ~/.aws/config |grep "\[profile"|sed -E 's/\[profile(.)//' 给 gateway] personal] DA] CX] 我知道可以添加一个管道,并使用us tr删除最后一个“]”或甚至cut也可以,但
“profile”
和“]”
之间的单词
我的内容
[profile gateway]
[profile personal]
[profile DA]
[profile CX]
为此我已经试过了
less ~/.aws/config |grep "\[profile"|sed -E 's/\[profile(.)//'
给
gateway]
personal]
DA]
CX]
我知道可以添加一个管道,并使用us tr删除最后一个
“]”
或甚至cut也可以,但是有人能帮我用上面的sed命令和regex删除最后一个“]”
你可以使用sed
:
sed-n's/*\[profile*\([^][]*\])./\1/p'~/.aws/config
详情:
-抑制默认行输出-n
-查找任何文本,*\[profile*\([^][]*\])./
,零个或多个空格,然后将除[profile
[/code>和
之外的任何零个或多个字符捕获到组1中,然后匹配其余文本]
-替换为组1值\1
-打印替换结果p
s='[配置文件网关]
[个人资料]
[个人资料]
[档案CX]'
sed-n's/*\[profile*\([^][]*\)./\1/p'如果可以将grep与-p
一起用于与Perl兼容的正则表达式:
less ~/.aws/config | grep -oP "\[profile \K[^][]+(?=])"
模式匹配:
\[profile
按字面匹配
\K
忘记目前匹配的内容
[^][]+
匹配除[
和]
(?=])
断言的正向前瞻(不匹配)]
对于示例内容,输出将是
gateway
personal
DA
CX
--在配置文件
和]之间提取单词
意味着最多可以删除配置文件
和]
上的内容,即^.*配置文件
和.*$
:
$ sed 's/^.*profile \|\].*$//g' file
输出:
gateway
personal
DA
CX
gateway
personal
DA
CX
请注意,如果只找到一个边界,它将被删除。在awk
中保持简单;通过将字段分隔符设置为[profile
或]
(根据显示的示例),并根据需要的输出打印列
awk -F'\\[profile |\\]' '{print $2}' Input_file
另一个较短的awk
解决方案:
awk-F'[]'$1==“[profile”{print$2}'~/.aws/config
网关
个人的
DA
CX
试图提取“profile”和“]”之间的单词
同样使用awk
作为profile
位于$1
末尾的条件:
awk '$1 ~ /profile$/ {sub(/]$/,"",$2);print $2}' file
gateway
personal
DA
CX
我相信有一个更有效/更复杂的解决方案,但您可以尝试在一个中使用3个sed命令:sed-E的/\[/;s/\]/;s/profile/'