LinuxQuestions.org
Register a domain and help support LQ
Go Back   LinuxQuestions.org > Forums > Linux Forums > Linux - Newbie
User Name
Password
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!

Notices


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

Rep: Reputation: Disabled
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
 
Old 11-05-2011, 08:47 AM   #2
JSkywalker
Member
 
Registered: Aug 2007
Distribution: openSUSE 12.1
Posts: 96

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

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
catkin
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
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.
 
Old 11-05-2011, 08:57 AM   #4
rajeshpvndd
LQ Newbie
 
Registered: Nov 2011
Posts: 3

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


Reply


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


All times are GMT -5. The time now is 10:31 AM.

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