【问题标题】:Extract version using shell commands使用 shell 命令提取版本
【发布时间】:2023-03-13 02:41:01
【问题描述】:

我正在尝试使用最合适的 shell 命令(如 grep、awk、sed、cut)从下面提到的 URL 中提取版本

https://abcd/efgh/1.1.3/hijkl/mnop    
https://abcd/efgh/hijkl/2.3.4.5/mnop    
https://abcd/3.4/efgh/hijkl/mnop

我希望从 URL 中单独提取版本(带点的数字),其中位置可能会如上例所示有所不同。寻找建议。

预期输出为:

1.1.3
2.3.4.5
3.4

【问题讨论】:

    标签: shell awk sed grep cut


    【解决方案1】:

    你可以使用这个grep:

    grep -Eo '[0-9]+(\.[0-9]+)+' file
    
    1.1.3
    2.3.4.5
    3.4
    

    【讨论】:

      【解决方案2】:

      使用awk,使用 GNU awk 中的示例进行编写和测试。

      awk 'match($0,/([0-9]+\.){1,}[0-9]+/){print substr($0,RSTART,RLENGTH)}' Input_file
      

      说明:为上述添加详细说明。

      awk '                               ##Starting awk program from here.
      match($0,/([0-9]+\.){1,}[0-9]+/){   ##using match function to match regex of ([0-9]+\.){1,}[0-9]+ in current line. 
        print substr($0,RSTART,RLENGTH)   ##Printing sub string of matched regex above, starting index is RSTART till value of RLENGTH here.
      }
      ' Input_file                        ##Mentioning Input_file name here.
      

      【讨论】:

        【解决方案3】:

        我会按照下面的方式使用 GNU AWK,让 file.txt 内容成为

        https://abcd/efgh/1.1.3/hijkl/mnop    
        https://abcd/efgh/hijkl/2.3.4.5/mnop    
        https://abcd/3.4/efgh/hijkl/mnop
        

        然后

        awk 'BEGIN{RS="[/\n]"}/^[.[:digit:]]+$/' file.txt
        

        输出

        1.1.3
        2.3.4.5
        3.4
        

        说明:我将行分隔符 (RS) 指定为 / 或换行符 (\n) 然后只打印仅包含 . 的行(即 / 或换行符和 / 或 / 和换行符之间的部分)或数字 - 为了达到这样的效果,我使用 ^$ 表示记录的开始和结束。

        【讨论】:

          猜你喜欢
          • 2017-12-03
          • 1970-01-01
          • 1970-01-01
          • 2020-01-22
          • 1970-01-01
          • 2017-10-12
          • 1970-01-01
          • 2012-10-01
          • 1970-01-01
          相关资源
          最近更新 更多