Reputation: 51
I have been trying to extract part of string in bash. I'm using it on Windows 10. Basically I want to remove "artifacts/" sfscripts_artifact_ and ".zip"
Original String
artifacts/online-order-api_sfscripts_artifact_1.5.6-6.zip
I've tried
input="artifacts/online-order-api_sfscripts_artifact_1.5.6-6.zip"
echo "${input//[^0-9.-]/}"
Output
--1.5.6-6.
Expected Output
online-order-api 1.5.6-6
Upvotes: 1
Views: 141
Reputation: 2805
mawk 'sub("_.+_"," ",$!(NF=NF))' OFS= FS='^.+/|[.][^.]+$'
online-order-api 1.5.6-6
Upvotes: -1
Reputation: 10123
A solution in pure bash
using the =~
operator.
[[ $input =~ .*/([^_]*).*_(.*)\.[^.]*$ ]] &&
echo "${BASH_REMATCH[1]} ${BASH_REMATCH[2]}"
prints out
online-order-api 1.5.6-6
with the given input.
Upvotes: 1
Reputation: 91
As a general solution using only variable expansion, consider:
input='artifacts/online-order-api_sfscripts_artifact_1.5.6-6.zip'
part0=${input%%_*}
part0=${part0##*/}
part1=${input##*_}
part1=${part1%.*}
echo "${part0} ${part1}"
Output:
online-order-api 1.5.6-6
Upvotes: 2
Reputation: 26471
Similar to the answer of adebayo10k, but in the order indicated by the user:
# Remove .zip from the end
tmp0="${input%.zip}"
# Remove path
tmp1="${tmp0##*/}"
# Extract version (remove everything before last underscore)
version="${tmp1##*_}"
# Extract name (remove everything after first underscore)
name="${tmp1%%_*}"
# print stuff
echo "${name}" "${version}"
Upvotes: 2
Reputation: 22225
Given your input,
echo ${input#artifacts/}
seems to me the simplest approach. This uses your assumption that you know already that the preceding path name is artifacts and leaves input
unchagned if it has a different structure. If you want to remove any starting directory name, you can do a
echo ${input#*/}
Upvotes: 0
Reputation: 785008
You may use this awk
solution:
s='artifacts/online-order-api_sfscripts_artifact_1.5.6-6.zip'
awk -F_ '{gsub(/^[^\/]*\/|\.[^.]*$/, ""); print $1, $NF}' <<< "$s"
online-order-api 1.5.6-6
Or else this sed
solution:
sed -E 's~^[^/]*/|\.[^.]+$~~g; s~(_[^_]+){2}_~ ~;' <<< "$s"
online-order-api 1.5.6-6
Upvotes: 3