INTELLIGENT WORK FORUMS
FOR COMPUTER PROFESSIONALS

Log In

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips Forums!
  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It's Free!

*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

Jobs

awk: print lines only when two lines with $NF == "string" found.

awk: print lines only when two lines with $NF == "string" found.

awk: print lines only when two lines with $NF == "string" found.

(OP)

hello,

print no line if only one or more than two has been found.

$ echo "1 2 3 stringA\n3 4 5 stringA"|awk '$NF == "stringA"'
1 2 3 stringA
3 4 5 stringA

current workaround:
TEST_INPUT="1 2 3 stringA\n3 4 5 stringB"
if [ `echo ${TEST_INPUT}|awk '$NF == "stringA"'|wc -l` -eq 2 ]
then
echo ${TEST_INPUT}|awk '$NF == "stringA"'
fi

can it be done with the only 'awk' command in:

echo "1 2 3 stringA\n3 4 5 stringB"|awk '$NF == "stringA"'

RE: awk: print lines only when two lines with $NF == "string" found.

Hi

This is a typical case for double passing : first just count, when just output :

CODE --> command-line

awk 'FNR==NR{$NF=="stringA"&&c++;next}c==2&&$NF=="stringA"' /input/file /input/file 

In case your input will come from the standard input, will need the shell's process substitution feature :

CODE --> command-line

awk 'FNR==NR{$NF=="stringA"&&c++;next}c==2&&$NF=="stringA"' <( echo "$TEST_INPUT" ) <( echo "$TEST_INPUT" ) 

In case the input is huge, is preferable to use optimized code, even if it is abit longer :

CODE --> command-line

awk 'FNR==NR{$NF=="stringA"&&c++;next}FNR==1&&c!=2{exit}$NF=="stringA"' /input/file /input/file

# or

awk 'FNR==NR{$NF=="stringA"&&c++;next}FNR==1&&c!=2{exit}$NF=="stringA"' <( echo "$TEST_INPUT" ) <( echo "$TEST_INPUT" ) 

Feherke.
http://feherke.github.com/

Red Flag This Post

Please let us know here why this post is inappropriate. Reasons such as off-topic, duplicates, flames, illegal, vulgar, or students posting their homework.

Red Flag Submitted

Thank you for helping keep Tek-Tips Forums free from inappropriate posts.
The Tek-Tips staff will check this out and take appropriate action.

Reply To This Thread

Posting in the Tek-Tips forums is a member-only feature.

Click Here to join Tek-Tips and talk with other members!

Resources

Close Box

Join Tek-Tips® Today!

Join your peers on the Internet's largest technical computer professional community.
It's easy to join and it's free.

Here's Why Members Love Tek-Tips Forums:

Register now while it's still free!

Already a member? Close this window and log in.

Join Us             Close