LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Find position of specific word in a line (https://www.linuxquestions.org/questions/linux-newbie-8/find-position-of-specific-word-in-a-line-912003/)

rajeshpvndd 11-05-2011 07:38 AM

Find position of specific word in a line
 
Hi
I have a line, aa bbb c dddd eeeee. How to read the position of the word "dddd", as "4" in bash. Please help.
Thanks

JSkywalker 11-05-2011 07:47 AM

Code:

echo "aa bbb c dddd eeeee" | awk -v t="dddd" '{ for (x=1; x<=NF; x++) { if ($x==t) { print "x=" x; exit(0) }} exit(-1);}'

catkin 11-05-2011 07:53 AM

Or a pure bash solution
Code:

#!/bin/bash
line='aa bbb c dddd eeeee'
word='dddd'
array=( $line )
for (( i=0; i<${#array[*]}; i++ ))
do
        [[ ${array[i]} = $word ]] && break
done
echo "$i"

The output is zero-based and it does not deal with the case where the word does not appear in the line.

rajeshpvndd 11-05-2011 07:57 AM

Thanks
It worked...


All times are GMT -5. The time now is 06:42 AM.