uldics
uldics

Reputation: 134

How to remove a known last part from commands output string in one line?

To rephrase - I want to use Bash command substitution and string substitution in the same line.

My actual commands are longer, but the ridiculous use of echo here is just a "substitution" for shortness and acts the same - with same errors ;)

I know we can use a Bash command to produce it's output string as a parameter for another command like this:

echo "$(echo "aahahah</ddd>")"
aahahah</ddd>

I also know we can remove last known part of a string like this:

var="aahahah</ddd>"; echo "${var%</ddd>}"
aahahah

I am trying to write a command where one command gives a string output, where I want to remove last part, which is known.

echo "${$(echo "aahahah</ddd>")%</ddd>}"
-bash: ${$(echo "aahahah</ddd>")%</ddd>}: bad substitution

It might be the order of things happening or substitution only works on variables or hardcoded strings. But I suspect just me missing something and it is possible.

How do I make it work? Why doesn't it work?

Upvotes: 1

Views: 90

Answers (2)

Quas&#237;modo
Quas&#237;modo

Reputation: 4004

When a dollar sign as in $word or equivalently ${word} is used, it asks for word's content. This is called parameter expansion, as per man bash.

You may write var="aahahah</ddd>"; echo "${var%</ddd>}": That expands var and performs a special suffix operation before returning the value.

However, you may not write echo "${$(echo "aahahah</ddd>")%</ddd>}" because there is nothing to expand once $(echo "aahahah</ddd>") is evaluated.

From man bash (my emphasis):

${parameter%word}

Remove matching suffix pattern. The word is expanded to produce a pattern just as in pathname expansion. If the pattern matches a trailing portion of the expanded value of parameter, then the result of the expansion is the expanded value of parameter with the shortest matching pattern (the ''%'' case) or the longest matching pattern (the ''%%'' case) deleted.

Upvotes: 1

Ivan
Ivan

Reputation: 7317

Combine your commands like this

var=$(echo "aahahah</ddd>")
echo ${var/'</ddd>'}

Upvotes: 1

Related Questions