How to resolve the algorithm Search a list step by step in the UNIX Shell programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Search a list step by step in the UNIX Shell programming language
Table of Contents
Problem Statement
Find the index of a string (needle) in an indexable, ordered collection of strings (haystack). Raise an exception if the needle is missing. If there is more than one occurrence then return the smallest index to the needle. Return the largest index to a needle that has multiple occurrences in the haystack.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Search a list step by step in the UNIX Shell programming language
Source code in the unix programming language
if [ $1 ];then
haystack="Zip Zag Wally Ronald Bush Krusty Charlie Bush Bozo"
index=$(echo $haystack|tr " " "\n"|grep -in "^$1$")
if [ $? = 0 ];then
quantity_of_hits=$(echo $index|tr " " "\n"|wc -l|tr -d " ")
first_index=$(echo $index|cut -f 1 -d ":")
if [ $quantity_of_hits = 1 ];then
echo The sole index for $1 is: $first_index
else
echo The smallest index for $1 is: $first_index
greatest_index=$(echo $index|tr " " "\n"|tail -1|cut -f 1 -d ":")
echo "The greatest index for $1 is: $greatest_index";fi
else echo $1 is absent from haystatck.;fi
else echo Must provide string to find in haystack.;fi
You may also check:How to resolve the algorithm Collections step by step in the Phix programming language
You may also check:How to resolve the algorithm Play recorded sounds step by step in the FutureBasic programming language
You may also check:How to resolve the algorithm Special variables step by step in the UNIX Shell programming language
You may also check:How to resolve the algorithm Return multiple values step by step in the JavaScript programming language
You may also check:How to resolve the algorithm Pinstripe/Printer step by step in the Racket programming language