Download your favorite Linux distribution at LQ ISO.
Go Back > Forums > Linux Forums > Linux - Newbie
User Name
Linux - Newbie This Linux forum is for members that are new to Linux.
Just starting out and have a question? If it is not in the man pages or the how-to's this is the place!


  Search this Thread
Old 11-05-2011, 08:38 AM   #1
LQ Newbie
Registered: Nov 2011
Posts: 3

Rep: Reputation: Disabled
Find position of specific word in a line

I have a line, aa bbb c dddd eeeee. How to read the position of the word "dddd", as "4" in bash. Please help.
Old 11-05-2011, 08:47 AM   #2
Registered: Aug 2007
Distribution: openSUSE 12.1
Posts: 96

Rep: Reputation: 24
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);}'

Last edited by JSkywalker; 11-05-2011 at 09:20 AM. Reason: optimized code if word not found
Old 11-05-2011, 08:53 AM   #3
LQ 5k Club
Registered: Dec 2008
Location: Tamil Nadu, India
Distribution: Debian
Posts: 8,576
Blog Entries: 31

Rep: Reputation: 1195Reputation: 1195Reputation: 1195Reputation: 1195Reputation: 1195Reputation: 1195Reputation: 1195Reputation: 1195Reputation: 1195
Or a pure bash solution
line='aa bbb c dddd eeeee'
array=( $line )
for (( i=0; i<${#array[*]}; i++ ))
	[[ ${array[i]} = $word ]] && break
echo "$i"
The output is zero-based and it does not deal with the case where the word does not appear in the line.
Old 11-05-2011, 08:57 AM   #4
LQ Newbie
Registered: Nov 2011
Posts: 3

Original Poster
Rep: Reputation: Disabled
It worked...


Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off

Similar Threads
Thread Thread Starter Forum Replies Last Post
How to find the position of the first space in a line? emili1001 Linux - Newbie 2 08-08-2011 02:02 PM
[SOLVED] command to find a specific word in directories and subdirectories? siranjeevi Linux - Newbie 4 06-09-2010 10:19 AM
How to find occurance of word in one line atul_sp Linux - Server 5 07-21-2008 02:20 PM
shell script to find an word or words from a line rakesh.tandur Linux - General 5 05-13-2008 02:57 PM
Command line tools to Find files with specific text naps Linux - Software 5 11-15-2004 05:46 AM > Forums > Linux Forums > Linux - Newbie

All times are GMT -5. The time now is 06:46 PM.

Main Menu
Write for LQ is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Facebook: linuxquestions Google+: linuxquestions
Open Source Consulting | Domain Registration