【问题标题】:Extract each word immediately preceded by an asterisk提取前面有星号的每个单词
【发布时间】:2020-12-13 22:26:32
【问题描述】:

我是一名计算机科学专业的学生,​​他们要求我们使用 sed 命令从 lpoptions -l 命令产生的文本中提取一个单词

PageSize/Page Size: Letter *A4 11x17 A3 A5 B5 Env10 EnvC5 EnvDL EnvISOB5 EnvMonarch Executive Legal
Resolution/Resolution: *default 150x150dpi 300x300dpi 600x600dpi 1200x600dpi 1200x1200dpi 2400x600dpi 2400x1200dpi 2400x2400dpi
InputSlot/Media Source: Default Tray1 *Tray2 Tray3 Manual
Duplex/Double-Sided Printing: DuplexNoTumble DuplexTumble *None
PreFilter/GhostScript pre-filtering: EmbedFonts Level1 Level2 *No

我只需要得到前面有* 的单词,但我找不到如何用 sed 来做,我已经用 cut 做了,这更容易,但我想用 sed 知道它。 我期待:

A4
default
Tray2
None
No

我试过了:

sed -E 's/.*\*=(\S+).*/\1/'

但它什么也没做。

【问题讨论】:

    标签: awk sed


    【解决方案1】:

    对于任何 POSIX sed(假设星号后面总是至少有一个非空格字符):

    sed 's/.*\*\([^[:space:]]*\).*/\1/'
    

    使用 GNU sed 会是:

    sed -E 's/.*\*(\S+).*/\1/'
    

    鉴于您的样本,它们都输出:

    A4
    default
    Tray2
    None
    No
    

    【讨论】:

    • 谨慎的做法是关闭隐式打印-n 并将p 标志添加到替换命令中,以便只打印匹配项。
    【解决方案2】:

    如果您对awk 解决方案没问题,请尝试关注。

    awk '{for(i=1;i<=NF;i++){if($i~/^\*/){sub(/^\*/,"",$i);print $i}}}' Input_file
    

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

    awk '                      ##Starting awk program from here.
    {
      for(i=1;i<=NF;i++){      ##Starting for loop here to loop through each field of currnet line.
        if($i~/^\*/){          ##Checking condition if line starts from * then do following.
          sub(/^\*/,"",$i)     ##Substituting starting * with NULL in current field.
          print $i             ##Printing current field value here.
        }
      }
    }
    ' Input_file               ##Mentioning Input_file name here.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-17
      相关资源
      最近更新 更多