简体   繁体   English

如何使用 Bash 提取字符串的一部分

[英]How to Extract Part of a String using Bash

I have been trying to extract part of string in bash.我一直在尝试提取 bash 中的部分字符串。 I'm using it on Windows 10. Basically I want to remove "artifacts/" sfscripts_artifact _ and ".zip"我在 Windows 10 上使用它。基本上我想删除“artifacts/” sfscripts_artifact_和“.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 Output

--1.5.6-6.

Expected Output预计 Output

online-order-api 1.5.6-6

You may use this awk solution:您可以使用此awk解决方案:

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解决方案:

sed -E 's~^[^/]*/|\.[^.]+$~~g; s~(_[^_]+){2}_~ ~;' <<< "$s"

online-order-api 1.5.6-6

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: Output:

online-order-api 1.5.6-6

Similar to the answer of adebayo10k, but in the order indicated by the user:类似于 adebayo10k 的答案,但按照用户指示的顺序:

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

A solution in pure bash using the =~ operator.使用=~运算符的纯bash解决方案。

[[ $input =~ .*/([^_]*).*_(.*)\.[^.]*$ ]] &&
    echo "${BASH_REMATCH[1]} ${BASH_REMATCH[2]}"

prints out打印出来

online-order-api 1.5.6-6

with the given input.使用给定的输入。

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.这使用您的假设,即您已经知道前面的路径名称是工件,并且如果input具有不同的结构,则它会保持不变。 If you want to remove any starting directory name, you can do a如果要删除任何起始目录名称,可以执行

echo ${input#*/}
mawk 'sub("_.+_"," ",$.(NF=NF))' OFS= FS='^.+/|[.][^.]+$'
online-order-api 1.5.6-6

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM