[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: extract values from a string



On Fri, Apr 15, 2022, 9:37 PM wilson <info@bigcount.xyz> wrote:
Hello

in shell script, how can I use regex to extract values from a string?
maybe value types transformation should be required.


for instance the string: "black berry 12".
I want go get the name: black berry [String]
the price: 12 [Int]

So you have programming language skills. Look at the info-command-based doc for bash. Read the sections about shell pattern-matching operators. Realize that there are more than one type of that. For example the crippled filename pattern matching on many commands, not really regular expressions.

Everything you want to do can be done. The syntax is clunkier than other mechanisms.

I did this in other language such as java/scala:

scala> val regex = """(.+)\s+(\d+)""".r
val regex: scala.util.matching.Regex = (.+)\s+(\d+)

scala> str match {
      |   case regex(name,price) => (name,price.toInt)
      | }
val res2: (String, Int) = (black berry,12)


But sometimes for a simple task I won't want to write a java program.
so what's the shell solution?

Thanks


Reply to: