Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract each word immediately preceded by an asterisk

Tags:

sed

awk

I'm a computer science student and they asked us to extract a word from the text that results from the lpoptions -l command using the sed command so

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

I need to get only the words preceded by a *, but I can't find how to do it with sed, I already did it using cut which is easier but I want to know it with sed. I expect :

A4
default
Tray2
None
No

and I had tried :

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

but it didn't do anything.

like image 963
abmis Avatar asked Dec 17 '22 12:12

abmis


2 Answers

With any POSIX sed (assuming there is always at least one non-space character following the asterisk):

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

With GNU sed it'd be:

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

Given your sample they both output:

A4
default
Tray2
None
No
like image 172
oguz ismail Avatar answered Feb 01 '23 15:02

oguz ismail


Could you please try following, in case you are ok with awk solution.

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

Explanation: Adding detailed explanation for above.

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.
like image 33
RavinderSingh13 Avatar answered Feb 01 '23 15:02

RavinderSingh13