Skip to content
Advertisement

awk the previous and current line only if equal to string

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}'

Advertisement

Answer

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
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement