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 :-)

4 comments:

Unknown 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

Unknown said...

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

awk -F ","

Hope this helps.

Unknown said...

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

Hare Krishna !!
Sudhakar

Unknown said...


isset() {
eval "case \${${1}++} in ? ) :;; * ) false;; esac"
}

incr() {
eval "$1=\`expr \"\${$1}\" + 1\`"
}

LN=1

unset hdrfutr_eko

srch_word=${1:-'times'}

while IFS= read -r line
do
case $line in
"$srch_word" |\
"$srch_word "* |\
*" $srch_word "* |\
*" $srch_word" )
${hdrfutr_eko+:} echo "Word \"$srch_word\" is found in"
set -f; set X $line; CN=$#; shift
hdrfutr_eko=
while case $# in 0 ) break;; esac; do
case $1 in
"$srch_word" ) echo "line number $LN |column number" "$(expr "$CN" - "$#")";;
esac
shift
done;;
esac
incr LN
done < testfile1.txt
isset hdrfutr_eko && echo 'Done!!'

© Jadu Saikia www.UNIXCL.com