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/'