【问题标题】:Sed: Match, remove and replace in one sed callSed:在一次 sed 调用中匹配、删除和替换
【发布时间】:2014-10-12 17:18:05
【问题描述】:

假设我有一个字符串:

Image.Resolution=1024x768,800x600,640x480,480x360,320x240,240x180,160x120,1280x720

我想使用sed 删除第一部分 (Image.Resolution=),然后用逗号分隔其余部分,以便我可以将所有分辨率放入 bash 数组中。

我知道如何分两步完成(两个sed 调用),例如:

sed 's/Image.Resolution=//g' | sed 's/,/ /g'.

但作为练习,我想知道是否有办法一次性完成。

提前谢谢你。

【问题讨论】:

    标签: arrays bash sed split


    【解决方案1】:

    只需在命令之间加上;

    sed 's/Image.Resolution=//g; s/,/ /g'
    

    来自info sed

    3 `sed' Programs
    ****************
    
    A `sed' program consists of one or more `sed' commands, passed in by
    one or more of the `-e', `-f', `--expression', and `--file' options, or
    the first non-option argument if zero of these options are used.  This
    document will refer to "the" `sed' script; this is understood to mean
    the in-order catenation of all of the SCRIPTs and SCRIPT-FILEs passed
    in.
    
       Commands within a SCRIPT or SCRIPT-FILE can be separated by
    semicolons (`;') or newlines (ASCII 10).  Some commands, due to their
    syntax, cannot be followed by semicolons working as command separators
    and thus should be terminated with newlines or be placed at the end of
    a SCRIPT or SCRIPT-FILE.  Commands can also be preceded with optional
    non-significant whitespace characters.
    

    【讨论】:

      【解决方案2】:

      这个awk也可以工作:

      s='Image.Resolution=1024x768,800x600,640x480,480x360,320x240,240x180,160x120,1280x720'
      awk -F '[=,]' '{$1=""; sub(/^ */, "")} 1' <<< "$s"
      1024x768 800x600 640x480 480x360 320x240 240x180 160x120 1280x720
      

      【讨论】:

      • 其实这是一个好主意,我打算这样做(嗯,有点...$(awk -F '[=,]' '{$1=""; sub(/^[0-9]{1,}x[0-9]{1,}/, "")} 1' &lt;&lt;&lt; "$s"))因为这样我可以确保决议的形式[:digit:]x[:digit:],但列维茨基的回答更好地回答了这个问题(我的措辞方式)
      【解决方案3】:

      对于这个具体的例子,你可以用简短的方式来做:

      sed 's/[^x0-9]/ /g'
      

      x='Image.Resolution=1024x768,800x600,640x480,480x360,320x240,240x180,160x120,1280x720'
      y=(${x//[^x0-9]/ })
      

      将删除除x 和数字0-9 之外的所有内容,因此输出(或数组y)为

      1024x768 800x600 640x480 480x360 320x240 240x180 160x120 1280x720
      

      【讨论】:

        【解决方案4】:
        x="Image.Resolution=1024x768,800x600,640x480,480x360,320x240,240x180,160x120,1280x720"
        x=${x#*=}             # remove left part including =
        array=(${x//,/ })     # replace all `,` with whitespace and create array
        echo ${array[@]}      # print array $array
        

        输出:

        1024x768 800x600 640x480 480x360 320x240 240x180 160x120 1280x720

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-06-09
          • 2012-02-27
          • 2015-11-16
          • 2022-01-18
          • 2012-09-19
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多