LinuxQuestions.org
Visit Jeremy's Blog.
Home Forums Tutorials Articles Register
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices


Reply
  Search this Thread
Old 02-21-2020, 03:50 PM   #1
pedropt
Member
 
Registered: Aug 2014
Distribution: Devuan
Posts: 345

Rep: Reputation: Disabled
Count a position of word in variable


on this code
Quote:
var="aaa bbb ccc ddd eeee"
how can i know that bbb is the 2nd word in variable ?

thanks
 
Old 02-21-2020, 04:10 PM   #2
petelq
Member
 
Registered: Aug 2008
Location: Yorkshire
Distribution: openSUSE(Leap and Tumbleweed) and a (not so) regularly changing third and fourth
Posts: 627

Rep: Reputation: Disabled
Make the variable an array and then each group of letters becomes 0,1,2,3,4 in the array. Look up arrays in your bash tutorial. It's pretty staightforward.
 
Old 02-21-2020, 04:52 PM   #3
pedropt
Member
 
Registered: Aug 2014
Distribution: Devuan
Posts: 345

Original Poster
Rep: Reputation: Disabled
An array does not work for what i need because that variable is just an example .
 
Old 02-21-2020, 05:11 PM   #4
teckk
LQ Guru
 
Registered: Oct 2004
Distribution: Arch
Posts: 5,146
Blog Entries: 6

Rep: Reputation: 1834Reputation: 1834Reputation: 1834Reputation: 1834Reputation: 1834Reputation: 1834Reputation: 1834Reputation: 1834Reputation: 1834Reputation: 1834Reputation: 1834
Quote:
how can i know that bbb is the 2nd word in variable ?
It isn't. That is one variable. There are not multiple words in that.

You can parse it though.
Code:
var="aaa bbb ccc ddd eeee"

echo "$var"
aaa bbb ccc ddd eeee

echo "$var" | cut -d ' ' -f1
aaa

echo "$var" | cut -d ' ' -f2
bbb

echo "${var:4:3}"
bbb
Make an array
Code:
a=(aaa bbb ccc ddd eee)

echo "${a[@]}"
aaa bbb ccc ddd eee

for i in {0..5}; do
    echo "${a[$i]}"
done

aaa
bbb
ccc
ddd
eee
Post what you are trying to accomplish.
 
Old 02-21-2020, 05:13 PM   #5
SoftSprocket
Member
 
Registered: Nov 2014
Posts: 399

Rep: Reputation: Disabled
If you split the string on spaces and then compare the resulting strings in an indexed loop you will have the answer.
 
Old 02-21-2020, 05:34 PM   #6
pedropt
Member
 
Registered: Aug 2014
Distribution: Devuan
Posts: 345

Original Poster
Rep: Reputation: Disabled
Again , an array does not work for what i need .
That example is just an example , in reality that var will come with a lot of values that may or not appear depending on what user writes in terminal , and will also appear other values that i have to pick.

1st , forget array , one solution would be using tr according to SoftSprocket.

Code:
var="aaa bbb ccc ddd eee"
a1=$(echo "$var" | tr " " "\n" > tmp.file)
a2=$(grep -n "bbb" tmp.file | sed 's/[:].*$//'
)
echo "bbb is the number $a2 word"
However i will have a problem ahead , witch is :
bbb may not exist in variable but i have to look for it , and if i look for something that does not exist with grep and the -n switch then i will have an error .

Last edited by pedropt; 02-21-2020 at 06:44 PM.
 
Old 02-21-2020, 07:55 PM   #7
pedropt
Member
 
Registered: Aug 2014
Distribution: Devuan
Posts: 345

Original Poster
Rep: Reputation: Disabled
Well i found a way to deal with this issue .
Was using tr as i did before but with a few changes along the code that it makes no importance to post here , since my last code solves this issue .
 
Old 02-22-2020, 02:20 AM   #8
MadeInGermany
Senior Member
 
Registered: Dec 2011
Location: Simplicity
Posts: 2,808

Rep: Reputation: 1207Reputation: 1207Reputation: 1207Reputation: 1207Reputation: 1207Reputation: 1207Reputation: 1207Reputation: 1207Reputation: 1207
Code:
var="aaa bbb ccc ddd eee"
search="bbb"
a2=$(echo "$var" |
  tr -s " " "\n" |
  sed "/^$search\$/="
)
if [ -n "$a2" ]
then
  echo "$search is the number $a2 word"
else
  echo "$search not found"
fi
The a2 can be set as well with shell builtins:
Code:
a2=$(
  cnt=0
  set -f
  for word in $var
  do
    ((cnt+=1))
    if [ "$search" = "$word" ]
    then
      echo "$cnt"
      break
    fi
  done
)
As you see, the $( ) is a complete sub-shell.
It makes sense to put such lengthy code into a function, especially if you plan to use it several times.

Last edited by MadeInGermany; 02-22-2020 at 02:58 AM. Reason: Fix: compare with $word not $var
 
Old 02-22-2020, 04:46 AM   #9
petelq
Member
 
Registered: Aug 2008
Location: Yorkshire
Distribution: openSUSE(Leap and Tumbleweed) and a (not so) regularly changing third and fourth
Posts: 627

Rep: Reputation: Disabled
Quote:
Originally Posted by pedropt View Post
An array does not work for what i need because that variable is just an example .
You should have given us a better example because an array certainly would work with the example you gave.
 
2 members found this post helpful.
Old 02-22-2020, 06:29 PM   #10
boughtonp
Senior Member
 
Registered: Feb 2007
Location: UK
Distribution: Debian
Posts: 3,616

Rep: Reputation: 2555Reputation: 2555Reputation: 2555Reputation: 2555Reputation: 2555Reputation: 2555Reputation: 2555Reputation: 2555Reputation: 2555Reputation: 2555Reputation: 2555
Quote:
Originally Posted by pedropt View Post
1st , forget array , one solution would be using tr according to SoftSprocket.

Code:
var="aaa bbb ccc ddd eee"
a1=$(echo "$var" | tr " " "\n" > tmp.file)
a2=$(grep -n "bbb" tmp.file | sed 's/[:].*$//'
)
echo "bbb is the number $a2 word"
Simpler version of same thing:
Code:
var="aaa bbb ccc ddd eee"
a2=$(echo "$var" | tr " " "\n" | grep -n "bbb" | sed 's/:.*//')
echo "bbb is the number $a2 word"
but...

Quote:
However i will have a problem ahead , witch is :
bbb may not exist in variable but i have to look for it , and if i look for something that does not exist with grep and the -n switch then i will have an error .
You also have two other problems highlighted by var="aaa bbbb ccc bbb ddd eee bbb"


It's frustrating that no equivalent to ListFind(haystack,needle,delimiter) is provided natively by any CLI-based languages. Here's a quick Python implementation:
Code:
import sys;
  
try:
   haystack = sys.argv[1]
   needle = sys.argv[2]
   delim = sys.argv[3] if len(sys.argv) > 3 else " "
   pos = haystack.split(delim).index(needle)+1;
except:
   pos = 0;

print(pos)
It returns the first match, or zero if no matches:
Code:
$ python listfind.py "aaa bbb ccc ddd eeee" "bbb"
2
$ python listfind.py "aaa bbbb ccc bbb ddd eeee bbb" "bbb"
4
$ python listfind.py "aaa bbb ccc ddd eeee" "qqq"
0
 
Old 02-23-2020, 01:33 PM   #11
danielbmartin
Senior Member
 
Registered: Apr 2010
Location: Apex, NC, USA
Distribution: Mint 17.3
Posts: 1,881

Rep: Reputation: 660Reputation: 660Reputation: 660Reputation: 660Reputation: 660Reputation: 660
Quote:
Originally Posted by pedropt View Post
on this code

how can i know that bbb is the 2nd word in variable ?

thanks
Please clarify. Do you want a Yes/No answer to this question or a position number such as 0=not found, 2=found in second position?

Daniel B. Martin

.
 
Old 02-24-2020, 09:57 AM   #12
danielbmartin
Senior Member
 
Registered: Apr 2010
Location: Apex, NC, USA
Distribution: Mint 17.3
Posts: 1,881

Rep: Reputation: 660Reputation: 660Reputation: 660Reputation: 660Reputation: 660Reputation: 660
A solution for your consideration. No arrays. No loops.
Handles the "not found" case.

This program ...
Code:
#!/bin/bash   Daniel B. Martin   Feb20  

# To execute this program, launch a terminal session and enter:
#   bash /home/daniel/Desktop/LQfiles/dbm2152.bin
#
# This program inspired by ...
# https://www.linuxquestions.org/questions/programming-9/
#  count-a-position-of-word-in-variable-4175670031/

# var="aaa bbb ccc ddd eeee"
# how can i know that bbb is the 2nd word in variable ?
 
# Keywords: word position

# File identification
      Path=${0%%.*}
   OutFile=$Path"out.txt"

function WordPos () {
local n=$(cut -d " " -f1 <<<$*)  # n=needle
WordPos=$(tr " " "\n" <<<$* \
|nl -nln -v0                \
|grep -wm2 $n               \
|tail -n1                   \
|cut -d' ' -f1)
# The position of the needle in the haystack
#   is in the global variable WordPos.
# WordPos=0 means the needle was not found.
}  # End of function WordPos


haystack="aaa bbb ccc ddd eeee"

echo; echo "Example #1 of LQ Member danielbmartin."
needle="bbb"
echo 'Find this needle '$needle
echo '  in this haystack '$haystack
WordPos $needle $haystack
echo 'WordPos='$WordPos

echo; echo "Example #2 of LQ Member danielbmartin."
needle="cc"
echo 'Find this needle '$needle
echo '  in this haystack '$haystack
WordPos $needle $haystack
echo 'WordPos='$WordPos

echo; echo "Normal end of job."; echo; exit
... produced this result ...
Code:
Example #1 of LQ Member danielbmartin.
Find this needle bbb
  in this haystack aaa bbb ccc ddd eeee
WordPos=2

Example #2 of LQ Member danielbmartin.
Find this needle cc
  in this haystack aaa bbb ccc ddd eeee
WordPos=0

Normal end of job.
As always, corrections and constructive criticisms are invited.

Daniel B. Martin

.
 
Old 02-24-2020, 11:39 AM   #13
SoftSprocket
Member
 
Registered: Nov 2014
Posts: 399

Rep: Reputation: Disabled
I don't do any bash programming these days but it seems to me something like this would work:
Code:
#!/bin/bash


IFS=' ' read -ra splits <<< "$1"

searchStr="$2"
res=""

for i in "${!splits[@]}"; do
        if [ "${splits[$i]}" == "${searchStr}" ]; then
                res="$res$i "
        fi
done

printf "${res}\n"
Code:
$ ./position_in_string.sh "aaa bbb ccc bbbb bbb" "bbb"
1 4
Zero indexed of course.
 
  


Reply



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
regex for phrase like'word-word-word' Zero4 Linux - General 9 07-06-2019 06:36 AM
Microsoft Word - Automatic Selection Word Count? NotAComputerGuy General 8 10-29-2012 05:18 AM
[SOLVED] Find position of specific word in a line rajeshpvndd Linux - Newbie 3 11-05-2011 07:57 AM
variable length string using GD (word wrap, carriage return, word/character count)? frieza Programming 1 02-14-2009 05:21 PM
Inspected a character on a particular position in a word kushalkoolwal Programming 10 07-03-2008 08:37 PM

LinuxQuestions.org > Forums > Non-*NIX Forums > Programming

All times are GMT -5. The time now is 12:06 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
Open Source Consulting | Domain Registration