【问题标题】:Remove some character in the start and in the end using sed使用 sed 在开头和结尾删除一些字符
【发布时间】:2021-06-08 12:35:25
【问题描述】:

我正在尝试在 "profile ""]" 之间提取单词。

我的内容

[profile gateway]
[profile personal]
[profile DA]
[profile CX]

为此我已经尝试过

less ~/.aws/config |grep  "\[profile"|sed  -E 's/\[profile(.)//'

给了

gateway]
personal]
DA]
CX]

我知道可以添加一个管道和我们 tr 删除最后一个 "]" 甚至 cut 都可以,但有人可以帮助我使用上面的 sed 命令和正则表达式删除最后一个 "]"

【问题讨论】:

  • 我确信有一个更有效/更复杂的解决方案,但您可以尝试同时使用 3 个 sed 命令:sed -E 's/\[//;s/\]//;s/profile //'

标签: regex awk sed grep


【解决方案1】:

您可以使用sed

sed -n 's/.*\[profile *\([^][]*\).*/\1/p' ~/.aws/config

详情

  • -n - 禁止默认行输出
  • .*\[profile *\([^][]*\).*/ - 查找任何文本、[profile、零个或多个空格,然后将除 [] 之外的任何零个或多个字符捕获到第 1 组中,然后匹配文本的其余部分
  • \1 - 替换为第 1 组值
  • p - 打印替换结果。

查看online demo

s='[profile gateway]
[profile personal]
[profile DA]
[profile CX]'
sed -n 's/.*\[profile *\([^][]*\).*/\1/p' <<< "$s"

输出:

gateway
personal
DA
CX

使用 GNU grep

grep -oP '(?<=\[profile )[^]]+' ~/.aws/config

(?&lt;=\[profile )[^]]+ 正则表达式匹配紧接在profile 字符串前面的位置,然后匹配除] 之外的一个或多个字符。 -o 选项使grep 仅提取匹配项,P 启用 PCRE 正则表达式语法。

awk

你也可以使用awk:

awk '/^\[profile .*]$/{print substr($2, 0, length($2)-1)}' ~/.aws/config

它将查找以[profile 开头的所有行,并输出没有最后一个字符的第二个字段(即将被省略的] 字符)。

【讨论】:

    【解决方案2】:

    如果您可以将 grep 与 -P 一起使用以获得 Perl 兼容的正则表达式:

    less ~/.aws/config | grep -oP  "\[profile \K[^][]+(?=])"
    

    模式匹配:

    • \[profile 字面匹配
    • \K 忘记到目前为止匹配的内容
    • [^][]+ 匹配除 [] 之外的任何字符 1+ 次
    • (?=]) 肯定的前瞻断言(不匹配)]

    对于示例内容,输出将是

    gateway
    personal
    DA
    CX
    

    【讨论】:

      【解决方案3】:

      awk 中保持简单;通过将字段分隔符设置为 [profile](根据所示示例)并根据需要的输出打印列。

      awk -F'\\[profile |\\]' '{print $2}' Input_file
      

      【讨论】:

        【解决方案4】:

        - - 在profile ] 之间提取单词 意思是从profile ] 开始删除,即。 ^.*profile ].*$:

        $ sed 's/^.*profile \|\].*$//g' file
        

        输出:

        gateway
        personal
        DA
        CX
        

        注意,如果只找到一个边界,则将其删除。

        【讨论】:

          【解决方案5】:

          另一个更短的awk 解决方案:

          awk -F '[] ]' '$1 == "[profile" {print $2}' ~/.aws/config
          
          gateway
          personal
          DA
          CX
          

          【讨论】:

            【解决方案6】:

            trying to extract word between "profile " and "]"

            还使用awk 作为profile 位于$1 末尾的条件:

            awk '$1 ~ /profile$/ {sub(/]$/,"",$2);print $2}' file
            gateway
            personal
            DA
            CX
            

            【讨论】:

              猜你喜欢
              • 2011-01-16
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2012-01-04
              • 1970-01-01
              • 1970-01-01
              • 2013-01-12
              相关资源
              最近更新 更多