LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Deleting a word in variable not knowing if it will be capitalized or not (https://www.linuxquestions.org/questions/programming-9/deleting-a-word-in-variable-not-knowing-if-it-will-be-capitalized-or-not-4175702538/)

pedropt 10-24-2021 04:47 AM

Deleting a word in variable not knowing if it will be capitalized or not
 
in this text :

Quote:

I Think John went to the JOHN house
i can use :
Code:

var1="I Think John went to the house"
var2=$(echo "$var1" | sed 's/\<JOHN\>//g' | sed 's/\<John\>//g')
echo "$var2"

On this next code will fail because the Capitalized john is not in variable .
Code:

var1="I Think John is fine"
var2=$(echo "$var1" | sed 's/\<JOHN\>//g' | sed 's/\<John\>//g')
echo "$var2"

However if in next text the 2nd john does not show up then how can i write the code for the 2 options no matter if one of them does no show up in variable?

syg00 10-24-2021 05:39 AM

Depends on how specific the tests are - if only those 2, use alternation. If any variation of jOHn might arise, use a case-insensitive directive. See the doco from the GNU site or "info sed"; the manpage doesn't go this detail.

shruggy 10-24-2021 07:51 AM

There was a recent thread on case-insensitive matching in sed.

pedropt 10-25-2021 05:28 PM

Thanks

sundialsvcs 10-26-2021 01:21 PM

It's useful in general to read up on the topic of "regular expressions ('regexes')."

grail 10-27-2021 07:42 PM

Of course on something so trivial, you don't even need something like sed:
Code:

x='I Think John went to the JOHN house'
echo "${x//[Jj][Oo][Hh][Nn]/}"
I Think  went to the  house


MadeInGermany 10-30-2021 02:04 PM

And if you want to store it in a new variable, you can use a simple assignment
Code:

var1='I Think John went to the JOHN house'
var2=${var1//[Jj][Oo][Hh][Nn]/}
echo "$var2"



All times are GMT -5. The time now is 11:09 AM.