Get an equal string after a specific string in a shell script

Asked 1 years ago, Updated 1 years ago, 63 views

On Solaris, I want to use a shell script (bash) to extract a string from a single line of characters retrieved from a CSV format file up to a comma after an equal for a specific string, but I don't know how to write a regular expression.Could you please let me know?

(Example)
a=aaa, b=bbb, c=cc, d=ddd, e=ee
a=aaa, c=ccc, d=ddd, e=eee, f=ff
b=bbb, c=ccc, d=ddd, e=eee, g=ggg
    :

In the example above, I would like to get the "ddd" after "d=".
"d=" is required, but "a=" and "b=" are not required, so
There may be no data, and the order in which "d=" appears is not fixed.

bash shellscript solaris

2022-09-30 19:46

3 Answers

If you only want to use the built-in command of bash, please do the following:

$while IFS=, read-ral
  do
    for ((i=0;i<${#l[@]};i++))
    do
      [[${l[$i]}=~^d=.+]]&printf'%s\n'"${l[$i]#d=}"
    done
  done<data.csv

If you don't mind using GNU grep, you can do the following:

$grep-Po'(?<=,d=)|(?<=^d=))(.+?)(?=(,|$))'data.csv

However, if there is no value of d for either of them (the line below), nothing will be printed.

 a=aaa, b=bbb, c=cc, d=, e=eee

add

Regarding Solaris+sed, it might be good to combine it with the tr command as follows.

$tr, '\n'<data.csv | sed-n's/^d=//p'

Also, we don't have Solaris environment at hand, so we haven't confirmed the result yet.


2022-09-30 19:46

If I actually do it, I think I'll handle it like this quickly.

$grep-o'd=[^,]*'in.csv | sed-e's/^d=//'


2022-09-30 19:46


if sed
sed-n's/^.*d=\([^,]\+\).*$/\1/p'

Lines without 行d= が will be ignored.


2022-09-30 19:46

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.