Find the answer to your Linux question:
Results 1 to 3 of 3
Enjoy an ad free experience by logging in. Not a member yet? Register.
  1. #1

    print number of lines from list using awk

    I have this code

    while read line
        awk "/\<$line\>/{print NR}" file.txt  
    done <  words.txt
    and I want to write a one line code. Since I am new to awk could you please help me? Basically, I want to print the number of line that contains a specific word. The list of words is in words.txt (one word per line)
    I tried the following code but it doesn't work.

    awk 'NR==FNR{n[$1];next} /\<$1\>/{print NR} (FNR in n)'  words.txt file.txt

  2. #2
    Try this:
    awk 'FNR==NR{w[$1]=NR;next}{for(i=1;i<=NF;i++){if($i in w){ print FNR " " $i; next }}}' words.txt file.txt
    1. FNR==NR is a test that separates the first file from the second file.
    2. On TRUE, the first {} sets the "w" array from the first file word list.
    3. On FALSE, the second {} loops through each field, tests each field to be in "w", and, if TRUE, prints the line number of the second file.
    The "next" after the "print" is to keep from printing multiple times if a single line contains a word more then once.
    I print FNR instead of NR as NR represents the total number of lines processed across multiple files. FNR is the line number in the current file, which is what you want.

  3. #3

    Thumbs up

    Thanks a lot. I just test it and it works perfectly!!!!

  4. $spacer_open

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts