Find the answer to your Linux question:
Results 1 to 3 of 3
Hi, I have this code Code: while read line do awk "/\<$line\>/{print NR}" file.txt done < words.txt and I want to write a one line code. Since I am new ...
Enjoy an ad free experience by logging in. Not a member yet? Register.
  1. #1
    Just Joined!
    Join Date
    Apr 2012
    Posts
    58

    print number of lines from list using awk


    Hi,
    I have this code

    Code:
    while read line
      do
        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.

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

  2. #2
    Just Joined!
    Join Date
    Jan 2009
    Posts
    12
    Try this:
    Code:
    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.
    NOTES:
    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
    Just Joined!
    Join Date
    Apr 2012
    Posts
    58

    Thumbs up

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

  4. $spacer_open
    $spacer_close

Posting Permissions

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