Mike Pérez
Mike Pérez

Reputation: 201

What does this awk sentence mean?

I have the following sentence in awk

$ gawk '$2 == "-"  { print $1 }' file

I was wondering what thing this instruction exactly did because I can't parse exactly the words I need.

Edit: How can I do in order to skip the lines before the following astersiks? Let's say I have the following lines:

text
text
text                


            * * * * * * *

line1 - 
line2 -

And then I want to filter just

line1
line2

with the sentence I posted above...

$ gawk '$2 == "-"  { print $1 }' file

Thanks for your time and response!

Upvotes: 1

Views: 377

Answers (2)

Oli
Oli

Reputation: 601

Answer to the original question:

If the second column in a line from the file matches the string "-" then it prints out the first column of the line, columns are by default separated by spaces.

This would match and print out one:

one - two three

This would not:

one two three four

Answer to the revised question:

This code should do what you need after the match of the given string:

awk '/\* \* \* \* \* \* \*/{i++}i && $2 == "-" { print $1 }' data2.txt

Testing on this data gives the following output:

2two
2two

Upvotes: 1

qaphla
qaphla

Reputation: 4733

This will find all lines on which the second column (Separated by spaces) is a -, and will then print the first column.

The first part ($2 == "-") checks for the second column being a -, and then if that is the case, runs the attached {} block, which prints the first column ($0 being the whole line, and $1, $2, etc being the first, second, ... columns.)

Spaces are the separator here simply because they are the default separator in awk.

Edit: To do what you want to do now, try the following (Not the most elegant, but it should work.)

gawk 'BEGIN { p = 0 } { if (p != 0 && $2 == "-") { print $1 } else { p = ($0 == "* * * * * * *")? 1 : 0 } }'

Spread over more lines for clarity on what's happening:

gawk 'BEGIN { p = 0 }
            { if (p != 0 && $2 == "-")
                 { print $1 }
              else
                 { p = ($0 == "* * * * * * *")? 1 : 0 }
            }'

Upvotes: 3

Related Questions