1

The following is my test.log file

a   1020    491 513 1   0   0   52
a   1000    491 513 1   0   0   53
sa  4011    491 513 1   0   0   0
sa  4010    491 513 1   0   0   1
d   1000    508 0   0   0   0   53
d   1020    508 0   0   0   0   52
a   1000    508 513 1   0   0   54
a   1020    508 513 1   0   0   55
sa  4011    508 1026    2   0   0   2
sa  4010    508 1026    2   0   0   3
sd  4010    508 513 1   0   0   1   QIO1
sa  4021    508 513 1   0   0   1
d   1000    525 0   0   0   0   54
d   1020    525 0   0   0   0   55
sd  4021    525 0   0   0   0   1   QIO2
a   1000    525 513 1   0   0   57
a   1020    525 513 1   0   0   56
sa  4010    525 1026    2   0   0   5
sa  4011    525 1539    3   0   0   4
sd  4011    525 1026    2   0   0   0   QIO1
sa  4021    525 513 1   0   0   0
d   1000    542 0   0   0   0   57
sd  4021    542 0   0   0   0   0   QIO2
d   1020    542 0   0   0   0   56

I want to extract only lines that have (first column = sa or sd) and second columns equal to 4010 and 4011. I tried the following command.

cat test.log | grep "sa\|sd" | awk '{if ($2 = "4010"|| $2 ="4011")print}'

But it gives me wrong output.

My expected output is

sa  4011    491 513 1   0   0   0
sa  4010    491 513 1   0   0   1
sa  4011    508 1026    2   0   0   2
sa  4010    508 1026    2   0   0   3
sd  4010    508 513 1   0   0   1   QIO1
sa  4010    525 1026    2   0   0   5
sa  4011    525 1539    3   0   0   4
sd  4011    525 1026    2   0   0   0   QIO1

Can someone suggest where I am going wrong. Thanks

2 Answers 2

3

Be idiomatic, my friend:

awk '$1 ~ /^s(a|d)$/ && $2 ~ /^401[01]$/' file
#         ^^^^^^^^^           ^^^^^^^^^
#         sa or sd            4010 or 4011

It returns:

sa  4011    491 513 1   0   0   0
sa  4010    491 513 1   0   0   1
sa  4011    508 1026    2   0   0   2
sa  4010    508 1026    2   0   0   3
sd  4010    508 513 1   0   0   1   QIO1
sa  4010    525 1026    2   0   0   5
sa  4011    525 1539    3   0   0   4
sd  4011    525 1026    2   0   0   0   QIO1
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, for the explanation
@user2532296 I hope it is clear. Note things like awk '{if (condition) print}' can be squeezed to a mere awk 'condition'.
Why (a|d) but [01]? IMHO [ad] would make more sense.
0

You can do this entirely in grep:

$ grep -E '^s[ad]\s+401[01]' file
sa  4011    491 513 1   0   0   0
sa  4010    491 513 1   0   0   1
sa  4011    508 1026    2   0   0   2
sa  4010    508 1026    2   0   0   3
sd  4010    508 513 1   0   0   1   QIO1
sa  4010    525 1026    2   0   0   5
sa  4011    525 1539    3   0   0   4
sd  4011    525 1026    2   0   0   0   QIO1

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.