Preface
Goal: Utilizing BASH IFS for string processing.
4: Approach in Solving Unique
A custom example, that you can rewrite.
An Algorithm Case
Why reinvent the wheel?
The same reason as other article.
x:xs Pattern Matching
The same with other article as well.
Exclude Function
Consider array in code below:
declare -a tags=(
"60s" "jazz" "60s" "rock"
"70s" "rock" "70s" "pop")
The exclude
function is just a filter
.
We are going to remove array using diff ${tags[@]/$val}
.
With complete function as below
function exclude() {
local val=$1
shift
local tags=("$@")
local return=( ${tags[@]/$val} )
echo "${return[@]}"
}
Finally we can call them in main script.
and reformat the output using IFS
.
# Extract output to array
tags_ex=$(exclude "rock" ${tags[@]})
IFS=' '; read -a tags_ar <<< "${tags_ex[@]}"
IFS=":"; echo "${tags_ar[*]}"
With the result as below array
:
❯ ./11-exclude.sh
60s:jazz:60s:70s:70s:pop
Recursive Unique Function
With exclude
function above,
we can build unique
function recursively, as below code:
function unique() {
local l_tags=("$@")
if (( ${#l_tags[@]} <= 1 )); then
echo "${l_tags[@]}"
else
local head=${l_tags[0]}
local tail=${l_tags[@]:1}
local exclude=( ${tail[@]/$head} )
local uniq_temp=$(unique "${exclude[@]}")
local return=($head)
return+=(${uniq_temp[@]})
echo "${return[@]}"
fi
}
Instead of using previously explained exclude
function.
We can just efficiently use array diff.
Applying Unique to Simple Array
Now we can apply the method to our unique song challenge.
source ./MyHelperUnique.sh
declare -a tags=(
"60s" "jazz" "60s" "rock"
"70s" "rock" "70s" "pop")
# Extract output to array
tags_un=$(unique ${tags[@]})
IFS=' '; read -a tags_ar <<< "${tags_un[@]}"
IFS=":"; echo "${tags_ar[*]}"
With the same result as below
With the result as below array
:
❯ ./12-unique-a.sh
60s:jazz:rock:70s:pop
Applying Unique to data Structure
We can also apply the method to our unique song challenge.
function unique() {
local l_tags=("$@")
if (( ${#l_tags[@]} <= 1 )); then
echo "${l_tags[@]}"
else
local head=${l_tags[0]}
local tail=${l_tags[@]:1}
local exclude=( ${tail[@]/$head} )
local uniq_temp=$(unique "${exclude[@]}")
local return=($head)
return+=(${uniq_temp[@]})
echo "${return[@]}"
fi
}
With the result as below array
:
❯ ./12-unique-b.sh
60s:jazz:rock:70s:pop
What is Next 🤔?
Consider continue reading [ Fish Shell - Playing with Records - Part One ].