简体   繁体   中英

Bash Nested Substring Removal (Extraction)?

I have something similar in a script I'm writing:

CMD="/path/to/cmd,there.sh"
TMP="${CMD##*/}"
echo "${TMP%%,*}"

Is there a way to nest the substring removals in line 2 & 3, or produce the same result in one-line, in pure bash, without going out to another program? The length of ${CMD} is not static. To be clear, I want the output to be simply "cmd".

I've tried the below, with various forms of brackets and quotations, but get a syntax error. This is something (I think) was allowed but isn't in new versions of Bash.

echo "${${CMD##*/}%%,*}"

不幸的是,没有,不可能在bash中组合或嵌套字符串操作。

用bash:

[[ $CMD =~ .*/([^,]*) ]] && echo ${BASH_REMATCH[1]}

Shell parameter substitution is primitive in that they don't provide functionalities like nesting. However, nobody prevents you from doing a sed thing here.

cmd="/path/to/cmd,there.sh" # Use lower-case identifiers for user variables
cmd=$(sed -E 's#^.*/([^,]+),.*$#\1#' <<<"$cmd")

The <<< enables the use of herestrings in bash .

我发现zsh实际上支持嵌套的字符串操作,因此我实际上将脚本的解释器切换到zsh,并且以下代码可以正常工作:

echo "${${CMD##*/}%%,*}"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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