【问题标题】:How to extract strings between nth and mth occurence of a certain character in linux bash?如何在linux bash中提取某个字符的第n个和第m个出现之间的字符串?
【发布时间】:2020-02-05 19:25:54
【问题描述】:

文件 1 包含:

a:b:c:d:any words here:e:f:G

w/r "any words here" 可以是单个词、两个词、三个词等等。

我想获取第 4 个“:”和第 5 个“:”之间的字符串。所以,这将是“这里的任何单词”。

我最初的想法是将“:”替换为空格,然后使用 awk 打印.. 但是由于我要提取的字符串可以由多个单词组成,因此无法准确工作。

【问题讨论】:

  • use awk to print 可以选择分隔符。 awk -F: 使用cut
  • @KamilCuk 你能详细说明一下吗?谢谢!
  • echo 'a:b:c:d:any words here:e:f:G' |cut -f 5 -d:

标签: linux string bash


【解决方案1】:

cut 命令允许您根据分隔符分割一行,并从中提取必填字段

在你的例子中,

> echo 'a:b:c:d:any words here:e:f:G' |cut -f 5 -d:

应该给你

any words here

【讨论】:

    【解决方案2】:

    awk

    $ echo 'a:b:c:d:any words here:e:f:G' | awk -F: '{print $5}'
    any words here
    

    或者通过创建一个数组,将IFS更改为:

    $ IFS=: words=( $(echo 'a:b:c:d:any words here:e:f:G') ); echo ${words[4]}
    any words here
    

    【讨论】:

      【解决方案3】:

      如果只是 1 行输入,您可以使用 bash 正则表达式。如果你想返回超过 1 个字段,那就更痛苦了,但对于 1 个字段,这很容易:

      f=3
      [[ "1:2:3:4:5:6:7:8" =~ (^([^:]*:){$f,$f})([^:]*)(:|$) ]]
      echo "${BASH_REMATCH[3]}"
      4
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-12-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多