Visit Our UNIX and Linux User Community


How to check index of a array element in shell script?


 
Thread Tools Search this Thread
Top Forums Shell Programming and Scripting How to check index of a array element in shell script?
# 1  
Old 05-23-2010
Question How to check index of a array element in shell script?

Example - Script to find the index of a month from array

Code:
MONTHS="Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec"
set -A MON $MONTHS
A="Sun May 23 09:34:30 GMT 2010"
getMonth=`echo $A|cut -c5-7`  ##getMonth=May
Arrayindex_in_MONTHS_array= ????        # { 0,1,2,3,4 } - at fifth place

Output should come 4 => $Arrayindex_in_MONTHS_array

Thanks,
kuldeep
# 2  
Old 05-23-2010
In Bash:
Code:
#!/bin/bash

getIndex() {
	index=0
	while [ "${ARRAY[$index]}" != "$VALUE" ] && [ $index -lt "${#ARRAY[@]}" ]; do ((index++)); done
	if [ $index -lt "${#ARRAY[@]}" ]; then
		echo $index
	else
		echo 'Not Found'
	fi
}

ARRAY=(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec)
VALUE='May'

getIndex

exit 0

In Bash (simpler?):
Code:
#!/bin/bash

getIndex() {
	for ((index=0; index<${#ARRAY[@]}; index++)); do 
		if [ "${ARRAY[$index]}" = "$VALUE" ]; then
			echo $index
			return
		fi
	done
	echo 'Not Found'
}

ARRAY=(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec)
VALUE='May'

getIndex

exit 0

A third version, just a modified 2nd version:
Code:
#!/bin/bash

getIndex() {
	index=0; while ((index<${#ARRAY[*]})); do
		if [ "${ARRAY[$index]}" = "$VALUE" ]; then
			echo $index; return
		fi
	((index++)); done
	echo 'Not Found'; return 1
}

ARRAY=(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec)
VALUE='May'

getIndex

exit 0


Last edited by tukuyomi; 05-23-2010 at 11:23 AM.. Reason: Added a third code
# 3  
Old 05-23-2010
Another way to get the index (month number):
Code:
MONTHS="JanFebMarAprMayJunJulAugSepOctNovDec"
A="Sun May 23 09:34:30 GMT 2010"

MonthNumber=`echo $A | awk '{printf("%d\n", (index("JanFebMarAprMayJunJulAugSepOctNovDec",$2)+2)/3)}'`

# 4  
Old 05-23-2010
Code:
#!/bin/bash
MONTHS="Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec"
A="Sun <May 23 09:34:30 GMT 2010"
getMonth=`echo $A|cut -c5-7`  ##getMonth=May
SUB=${MONTHS%$getMonth*}
index_in_MONTHS=$((${#SUB}/4+1))       # { 0,1,2,3,4 } - at fifth place
echo index_in_MONTHS

# 5  
Old 05-24-2010
Hey Thanks All,
All post are really great.
It is working now.

---------- Post updated at 08:24 PM ---------- Previous update was at 01:45 PM ----------

any function to count the array element available in array ?
like in my script the MONTHS array has 12 element. i just want to store in in a variable so that i can run the loop accordingly.

Thanks
# 6  
Old 05-24-2010
Code:
echo ${#MON[*]}

# 7  
Old 05-24-2010
bash function IndexOf

Code:
IndexOf()    {
    local i=1 S=$1; shift
    while [ $S != $1 ]
    do    ((i++)); shift
        [ -z "$1" ] && { i=0; break; }
    done
    echo $i
}
# usage example
ARRAY=(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec)
VALUE='May'
IndexOf $VALUE ${ARRAY[@]}
# will echo 0 if not found


Previous Thread | Next Thread
Test Your Knowledge in Computers #651
Difficulty: Medium
Amanda the Panda is the mascot of MOTIF.
True or False?

10 More Discussions You Might Find Interesting

1. Shell Programming and Scripting

Awk: check element in array and it's value

Hello, I want to see if element exists in array, if so then, check it's corresponding value. Column 4 is position and column 1 is the chromosome for it. There are duplicates for one position on one chromosome. I want to check if same position exists on different chromosome: Data... (8 Replies)
Discussion started by: genome
8 Replies

2. Shell Programming and Scripting

Associative array index question

I am trying to assign indexes to an associative array in a for loop but I have to use an eval command to make it work, this doesn't seem correct I don't have to do this with regular arrays For example, the following assignment fails without the eval command: #! /bin/bash read -d "\0" -a... (19 Replies)
Discussion started by: Riker1204
19 Replies

3. UNIX for Advanced & Expert Users

Array Element

This question is for someone that's more familiar with Array Element. I need to know if the maximum array element that can be assigned is 1024 and if its so, Is there a workaround solution when the counter exceeded 1024? param_array="$param_nam" counter=$counter+1 #to avoid space... (3 Replies)
Discussion started by: cumeh1624
3 Replies

4. Shell Programming and Scripting

awk Search Array Element Return Index

Can you search AWK array elements and return each index value for that element. For example an array named car would have index make and element engine. I want to return all makes with engine size 1.6. Array woulld look like this: BMW 1.6 BMW 2.0 BMW 2.5 AUDI 1.8 AUDI 1.6 ... (11 Replies)
Discussion started by: u20sr
11 Replies

5. Shell Programming and Scripting

Perl: How to check whether my array contains element x

Hi All, I am new to perl I am stuck in simple problem I need your help I want to define a subroutine. sub check_if_entity_exists(@array_to_be_checked,$entityName) I have array as http-listener-1 http-listener-2 http-listener-3 http-listener-4 If i send http-listener-3 my... (1 Reply)
Discussion started by: javaholics
1 Replies

6. Shell Programming and Scripting

Help! Yet another check element in array Question

Greetings, DISCLAIMER: My shell scripting is rusty so my question may be borderline stupid. You've been warned. I need to create a script that a) lists the content of zip files in a directory and b) sends out an `exception` report. My ZIP files contain a control file (for load check). I want... (2 Replies)
Discussion started by: alan
2 Replies

7. Shell Programming and Scripting

awk array index help

$ cat file.txt A|X|20 A|Y|20 A|X|30 A|Z|20 B|X|10 A|Y|40 Summing up $NF based on first 2 fields, $ awk -F "|" 'BEGIN {OFS="|"} { sum += $NF } END { for (f in sum) print f,sum } ' file.txt o/p: A|X|50 A|Y|60 A|Z|20 (4 Replies)
Discussion started by: uwork72
4 Replies

8. UNIX for Dummies Questions & Answers

wh inode index starts from 1 unlike array index (0)

brothers why inode index starts from 1 unlike array inex which starts from 0 its a question from the design of unix operating system of maurice j.bach i need to know the answer urgently...someone help please (1 Reply)
Discussion started by: sairamdevotee
1 Replies

9. Filesystems, Disks and Memory

why the inode index of file system starts from 1 unlike array index(0)

why do inode indices starts from 1 unlike array indexes which starts from 0 its a question from "the design of unix operating system" of maurice j bach id be glad if i get to know the answer quickly :) (0 Replies)
Discussion started by: sairamdevotee
0 Replies

10. Shell Programming and Scripting

Using Awk in shell script to extract an index of a substring from a parent string

Hi All, I am new to this shell scripting world. Struck up with a problem, can anyone of you please pull me out of this. Requirement : Need to get the index of a substring from a parent string Eg : index("Sandy","dy") should return 4 or 3. My Approach : I used Awk function index to... (2 Replies)
Discussion started by: sandeepms17
2 Replies

Featured Tech Videos