1

I tried to use sed to capture numbers in a string with following script:

echo '["770001,德邦优化混合","750005,安信平稳增长混合发起A"]' | sed -n 's/.*"\(\d{6}\),/\1/p'

My expectation is echo

770001
750005

While nothing output. Why?

jasonxia23
  • 147
  • 1
  • 12
  • 2
    sed doesn't support \d.. use [0-9] instead.. `{}` needs to be escaped as well.. and there is greedy issue as well.. I feel `grep -o '[0-9]\{6\}'` is better suited here.. – Sundeep Jan 22 '18 at 11:49
  • @Sundeep thanks for your answer, that works. – jasonxia23 Jan 22 '18 at 11:54
  • 1
    Possible duplicate of [Can grep show only words that match search pattern?](https://stackoverflow.com/questions/1546711/can-grep-show-only-words-that-match-search-pattern) – Sundeep Jan 22 '18 at 11:57
  • @Sundeep, A little different i think, I was trying to use `sed` to get all capture groups – jasonxia23 Jan 22 '18 at 12:01
  • 1
    well you said my grep solution worked.. often cli questions will get answers with totally different tools.. if you want answer with sed only, then I'll retract my vote.. – Sundeep Jan 22 '18 at 12:05

1 Answers1

1

In case you are ok with awk then following awk may help you in same. Since I have old version of awk so I am using --re-interval if you have newer version of awk then you may not need it.

echo '["770001,德邦优化混合","750005,安信平稳增长混合发起A"]' |
awk --re-interval '{while(match($0,/[0-9]{6}/)){print substr($0,RSTART,RLENGTH);$0=substr($0,RSTART+RLENGTH+1)}}'

Output will be as follows.

770001
750005
RavinderSingh13
  • 130,504
  • 14
  • 57
  • 93