Issue
Having string of pattern:st2-api-alpha
wanted to trim them like st2-api
Basically wanted to remove the text followed by 2nd occurence on '-' for each string.
for (( i=1; i<${#all_containers_list[@]}; i++ )){
echo "trimmed[$i] - "${all_containers_list[i]}|cut -f1-3 -d'-'
temp="$(${all_containers_list[i]}| cut -f1-3 -d'-')"
echo "temp is:$temp"
all_containers_list[i]=$temp
echo "all_containers_list[$i] is ${all_containers_list[i]}"
}
when i echo:
trimmed[1] - st2-ui
/home/****/st2-monitoring/monitors/getAllContainerStatus_v1.1.sh: line 139: st2-ui-server-alpha: command not found
temp is:
all_containers_list[1] is
trimmed[2] - st2-api
/home/****/st2-monitoring/monitors/getAllContainerStatus_v1.1.sh: line 139: st2-api-alpha: command not found
temp is:
all_containers_list[2] is
trimmed[3] - st2-whiteboard
/home/****/st2-monitoring/monitors/getAllContainerStatus_v1.1.sh: line 139: st2-whiteboard-alpha: command not found
temp is:
all_containers_list[3] is
trimmed[4] - st2-aspose
/home/****/st2-monitoring/monitors/getAllContainerStatus_v1.1.sh: line 139: st2-aspose-alpha: command not found
temp is:
all_containers_list[4] is
trimmed[5] - determined_bassi
/home/****/st2-monitoring/monitors/getAllContainerStatus_v1.1.sh: line 139: determined_bassi: command not found
temp is:
all_containers_list[5] is
trimmed[6] - st2-ui
/home//st2-monitoring/monitors/getAllContainerStatus_v1.1.sh: line 139: st2-ui--alpha: command not found
temp is:
all_containers_list[6] is
echo "trimmed[$i] - "${all_containers_list[i]}|cut -f1-3 -d'-'
--- This is working fine.But the below assignment is not working
temp=$(${all_containers_list[i]}| cut -f1-3 -d'-')
Request your help to fix the same! OS is CentOS , bash script
Solution
I think calling subprocesses just for removing a part of a string, is a bit of an overkill. Assuming that you have stored your string in a variable, say
str=st2-api-alpha
you could simply do a
if [[ $str =~ [^-]*-[^-]* ]]
then
str=${BASH_REMATCH[0]}
fi
If the string does not contain a dash, it is left unchanged. You can trvially generalize this solution to your case of having an array of strings.
Answered By - user1934428 Answer Checked By - Mary Flores (WPSolving Volunteer)