Chris
Chris

Reputation: 11

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

Upvotes: 1

Views: 558

Answers (5)

Wouter
Wouter

Reputation: 26

If you want to write the script "in one line", just use ; or && to indicate the end of a line instead of a line-break:

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

or

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

A more elaborate answer about combining commands can be found below this question.

Disclaimer: I understand that it is debatable whether or not this is a one-liner. But if you are visiting this question looking for a way to throw this in bash, it may answer your question regardless.

Upvotes: 0

Chris
Chris

Reputation: 11

I've found that zsh actually supports nested string operations, so I actually switched the interpreter to zsh for my script and the below works fine:

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

Upvotes: 0

Cyrus
Cyrus

Reputation: 88563

With bash:

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

Upvotes: 1

sjsam
sjsam

Reputation: 21955

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.

Upvotes: 0

John Kugelman
John Kugelman

Reputation: 361564

Unfortunately, no, it's not possible to combine or nest string operations in bash.

Upvotes: 1

Related Questions