Tuesday, December 25, 2007

Finding Column Number where pattern is found - BASH Beginner


My testfile1.txt is just a dummy text file, I have to find at which line and in which column the word "times" occurred.


$ cat testfile1.txt
education times
times of india
happy days happy times
new era new morning
times group
say no to BAD


Here is a one liner:


$ awk 'BEGIN {print "Word \"times\" is found in "}
END {print "Done!!"}
{ for(i=1;i<=NF;i++){
if ($i ~ /times/)
{print "line number "NR,"|column number " i } }
}' testfile1.txt


Output:

Word "times" is found in
line number 1 |column number 2
line number 2 |column number 1
line number 3 |column number 4
line number 5 |column number 1
Done!!


MarRy ChrIstMas to all my readers :-)

3 comments:

Sudhakar Shrinivas said...

Hello

How do I find the column number and line number in a file for a pattern say "times" in a file where the file data are seperated by comma instead of space ..

Suppose my file.txt contains data as below

output,rsss,rfff,tttt
val1,1,2,3
val2,2,3,4

I want to know the column number of
key word tttt in the above file

Thanks
Sudhakar

Jadu Saikia said...

@Sudhakar, please use awk FS variable to specify your field separator. e.g.

awk -F ","

Hope this helps.

Sudhakar Shrinivas said...

Thank you Jadu Sakia.
I appreciate your help and personal time.
Thanks again

Hare Krishna !!
Sudhakar

© Jadu Saikia www.UNIXCL.com