【问题标题】:Find the first column which starts with a string查找以字符串开头的第一列
【发布时间】:2016-06-12 04:14:01
【问题描述】:

我有一个 bash 脚本,它将接收一个看起来像这样的字符串:

foo,user:johndoe,bar

值的顺序和数量未知,因此也可能是这样的:

bar,foo,baz,user:johndoe

我需要能够获取用户的名称——在本例中为johndoe

使用 grep,我得到的最接近的是:

$ echo "foo,user:johndoe,bar" | grep -o 'user:.*,'
user:johndoe,

但这也让我得到user:,,这是我不想要的。我是新手,不确定 grep 是否是我应该使用的工具,或者 awk 或其他更合适的工具。

【问题讨论】:

    标签: regex bash awk grep


    【解决方案1】:

    对于简单的替换,sed 可以:

    % echo "foo,user:johndoe,bar" | sed 's/.*user:\([^,]*\).*/\1/'
    johndoe
    

    以上内容将用您的用户替换整个字符串:

    s/
      .*                     # Match anything zero or more times
        user:                # Match literal user:
             \([^,]*\)       # Capture everything but , zero or more times in \1
                      .*     # Match to the end of the string
                        /\1/ # Replace with what we matched and saved in \1
    

    GNU Grep 还有一个-P 选项,可以启用支持lookbehinds 的PCRE:

    % echo "foo,user:johndoe,bar" | grep -Po '(?<=user:)[^,]*'
    johndoe
    

    -P 仍处于高度试验阶段,应尽可能避免使用。

    【讨论】:

      【解决方案2】:

      使用 awk:

      $ echo "foo,user:johndoe,bar" | awk -F: '$1=="user"{print $2}' RS=,
      johndoe
      

      工作原理

      • -F:

        这会将字段分隔符设置为:

      • $1=="user"{print $2}

        如果第一个字段是user,则打印第二个字段。

      • RS=,

        这会将记录分隔符设置为,

      【讨论】:

      • 有趣地使用FSRS 组合:-)
      【解决方案3】:
      echo "foo,user:johndoe,bar" | awk -F ":" '{print $2}' | awk -F "," '{print $1}'
      

      【讨论】:

        猜你喜欢
        • 2022-08-11
        • 1970-01-01
        • 2011-08-06
        • 1970-01-01
        • 2011-12-07
        • 2011-08-02
        • 1970-01-01
        • 2012-10-11
        • 1970-01-01
        相关资源
        最近更新 更多