1

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

6 Answers 6

3

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
Sign up to request clarification or add additional context in comments.

Comments

2

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}"

Comments

2

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

Comments

1

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.

Comments

0

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#*/}

Comments

-1
mawk 'sub("_.+_"," ",$!(NF=NF))' OFS= FS='^.+/|[.][^.]+$'
online-order-api 1.5.6-6

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.