提取紧接在星号前面的每个单词

abm*_*mis 4 awk sed

我是一名计算机科学专业的学生,​​他们要求我们使用 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
Run Code Online (Sandbox Code Playgroud)

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

A4
default
Tray2
None
No
Run Code Online (Sandbox Code Playgroud)

我试过:

sed -E 's/.*\*=(\S+).*/\1/'
Run Code Online (Sandbox Code Playgroud)

但它没有做任何事情。

ogu*_*ail 6

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

sed 's/.*\*\([^[:space:]]*\).*/\1/'
Run Code Online (Sandbox Code Playgroud)

使用 GNU sed 将是:

sed -E 's/.*\*(\S+).*/\1/'
Run Code Online (Sandbox Code Playgroud)

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

A4
default
Tray2
None
No
Run Code Online (Sandbox Code Playgroud)


Rav*_*h13 5

如果您对awk解决方案没问题,请尝试以下操作。

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

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

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.
Run Code Online (Sandbox Code Playgroud)