Home > Software design >  awk the previous and current line only if equal to string
awk the previous and current line only if equal to string

Time:07-21

I have the following lines in a file

shush1 120 60G
albi 0/0/60
shush2 120 120G
albi 0/20/60

I want to get the previous and current line, only if it start with albi. Means, output should look like:

shush1 120 60G albi 0/0/60
shush2 120 120G albi 0/20/60

I tried the below, but looks I'm missing something:

awk '{if($1 ~ "shush*") line0=$0 ; else if($1 ~ "albi*") print $line0,$0}'

CodePudding user response:

Assuming you do need to test "shush" as in your script, all you were doing wrong is trying to reference an awk variable as $var (shell syntax) instead of just var (awk, C, etc. syntax):

$ awk '{ if ($1 ~ /shush/) line0=$0; else if ($1 ~ /albi/) print line0, $0 }' file
shush1 120 60G albi 0/0/60
shush2 120 120G albi 0/20/60

You also have undesirable *s at the end of your regexps (which I assume you think mean "any other chars" but that's shell globbing syntax, not regexp syntax where * means repetitions of the previous character or expression) which I've removed above and were using string "..." instead of regexp /.../ delimiters but neither of those things was causing your script to fail.

You can get the output you show without testing shush though with either of these (or various other possibilities) depending on your requirements for the rainy day cases like back to back lines containing albi, etc.:

$ awk '$1 ~ /albi/{ print line0, $0 } { line0=$0 }' file
shush1 120 60G albi 0/0/60
shush2 120 120G albi 0/20/60

$ awk '$1 ~ /albi/{ print line0, $0; line0=""; next } { line0=$0 }' file
shush1 120 60G albi 0/0/60
shush2 120 120G albi 0/20/60

CodePudding user response:

$ awk '/^albi/{print p,$0}{p=$0}' file

Output:

shush1 120 60G albi 0/0/60
shush2 120 120G albi 0/20/60

Regarding your sample solution: You seem to be mixing awk and bash. Your sample solution in awk would be:

$ awk '{if($1 ~ /^shush/) line0=$0 ; else if($1 ~ /^albi/) print line0,$0}'
  • Related