【问题标题】:How to extract two different columns separated by different delimiters into the same line如何将由不同分隔符分隔的两个不同列提取到同一行中
【发布时间】:2017-09-09 08:22:40
【问题描述】:

我在 unix txt 文件中有以下数据集:

/this/is/a/directory_name/which/i/want:listen= tcp://someurl
/this/is/a/another_directory_name/which/i/want:listen= tcp://someotherurl

基本上预期的输出是:

directory_name <whitespace> tcp://someurl
another_directory_name <whitespace> tcp://someotherurl

以下是我正在尝试但只获取 url 或目录名的命令

cat the_file.txt|awk -F '/' '{print $5}'
cat the_file.txt|awk -F '=' '{print $2}'

有没有办法同时实现上述两个命令并在同一行中获得输出? 非常感谢

【问题讨论】:

    标签: bash shell unix awk scripting


    【解决方案1】:

    只需保留第一个命令,对第二个命令进行调整:split 基于= 的全文并打印第二个结果字段:

    $ awk -F'/' '{split($0, a,"="); print $5, a[2]}' file
    directory_name  tcp://someurl
    another_directory_name  tcp://someotherurl
    

    如果有很多=s,则为最后一个:

    $ awk -F'/' '{n=split($0, a,"="); print $5, a[n]}' file
    directory_name  tcp://someurl
    another_directory_name  tcp://someotherurl
    

    【讨论】:

    • awk '{split($1,a,"/"); print a[5], $NF}' file,甚至可以使用默认的FS。
    • 非常感谢@fedorqui 的这次调整,尤其是第二次调整。这将大大减轻我的工作:) split 参数还可以处理多个分隔符,即超过 2 个。
    • @Anurodh 是的,split() 可以采用多个分隔符。但是,您也可以考虑using awk multiple delimiters in FS。但这仅取决于您正在处理的上下文,没有更多细节很难说。
    • @fedorqui 不,$NF 中有//(试过了:)。
    • @JamesBrown 我喜欢your first suggestion,不错!根据您的第二条评论,我想提一下,我通常指的是 awk 中的多个分隔符,而不是它可以用于这个特定问题。
    【解决方案2】:

    与sed

    $ sed -E 's|^([^/]*/){4}([^/]+).*=|\2|' ip.txt 
    directory_name tcp://someurl
    another_directory_name tcp://someotherurl
    
    • -E 使用 ERE,某些版本需要 -r 代替
    • ^([^/]*/){4} 与必填字段之前的 / 匹配
    • ([^/]+)必填字段
    • .*= 直到最后一个 = 在行中
    • \2 替换为必填字段,在给定示例中tcp 之前有空格,如果不能保证,请使用s|^([^/]*/){4}([^/]+).*= *|\2 |

    【讨论】:

      【解决方案3】:
      $ awk '{split($1,d,"/"); print d[5], $2}' file
      directory_name tcp://someurl
      another_directory_name tcp://someotherurl
      

      【讨论】:

        猜你喜欢
        • 2020-03-29
        • 2020-08-22
        • 1970-01-01
        • 2019-12-10
        • 1970-01-01
        • 1970-01-01
        • 2020-06-30
        • 2020-05-29
        • 1970-01-01
        相关资源
        最近更新 更多