K. Weber
K. Weber

Reputation: 2773

Bash sed: replace tag within square brackets

In a bash script (newbie to bash), I have a variable like this: "this is a message [REL]" and I want to convert it to this: "this is a message".

I tryed native bash string manipulation, like CLEAN_MESSAGE=${MESSAGE#REL} and didn't work so I'm trying with sed, I followed a few posts like this one: How to replace paired square brackets with other syntax with sed? but no luck

This is my current status:

MESSAGE=$(cat $1) #A message with a tag [REL]
RELTAG=\[[REL]\] #A variable with regexp for tag, tryed \[REL\], \[(REL)\], \[\(REL\)\] and other variants
CLEAN_MESSAGE=$(echo "$MESSAGE" | sed "s/$RELTAG//") 
echo $CLEAN_MESSAGE

With some variants of the RELTAG I get EL] or [RE, but never the complete tag removed.

Help?

Upvotes: 1

Views: 77

Answers (1)

Sundeep
Sundeep

Reputation: 23667

Use % to remove at end of string

$ s='this is a message [REL]'
$ echo "${s% \[REL]}"
this is a message

$ # if variable contains the removal glob
$ r=' \[REL]'
$ echo "${s%$r}"
this is a message

See wooledge Parameter Expansion for further reading

Upvotes: 2

Related Questions