Find the answer to your Linux question:
Results 1 to 2 of 2
Hello Is there any command in linux to search for a word in a file and print its surrounding words - say the immediate next word and the word before ...
  1. #1
    Just Joined!
    Join Date
    May 2010
    Posts
    1

    Access before/after words

    Hello

    Is there any command in linux to search for a word in a file and print its surrounding words - say the immediate next word and the word before it.

    Can it be done using awk?
    Any other suggestions..

    Thanks in advance!

    (P.S : I apologize for posting my query in the wrong section earlier.)

  2. #2
    Linux Enthusiast
    Join Date
    Aug 2006
    Posts
    631
    One way:
    Code:
    awk -v var="myword" '$0 ~ var{
      for(i=1;i<NF;i++){if($i==var){print $(i-1) FS $(i+1)}}
    }' file

Posting Permissions

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