Search code examples
regexbashat-command

Bash regex that returns short alphanumeric operator name from AT command AT+COPS


I'm using a bash script with the AT command AT+COPS=? which returns the following string :

+COPS: (1,"Orange F","Orange","20801",2),(1,"Swisscom","Swisscom","22801",7),(1,"Swisscom","Swisscom","22801",2),(1,"Salt","Salt","22803",2),(1,"Sunrise","Sunrise","22802",2),(1,"Sunrise","Sunrise","22802",7),(1,"Sunrise","Sunrise","22802",0),(2,"Salt","Salt","22803",7),(1,"Free","Free","20815",2),(1,"F SFR","SFR","20810",7),(1,"F-Bouygues Telecom","BYTEL","20820",7),,(0-4),(0-2)

And I'm trying to find a regular expression to match every short alphanumeric operator names. So here, it's :

Orange Swisscom Swisscom Salt Sunrise Sunrise Sunrise Salt Free SFR BYTEL

For example, in the group

(1,"F-Bouygues Telecom","BYTEL","20820",7)

It's the 'BYTEL' part that is interesting. 'BYTEL' could be also lower-case chars and numbers.

I tried multiple solution but they are all not 100% matching. For the moment, I'm using :

 grep -oP '"([a-zA-z])\w+"'

but it would not work in some special cases and is matching also the long alphanumeric operator names (first name between quotes).


Solution

  • Try this sed variant

    sed 's/(/\n/g' file | sed -n 's/.,".*","\(.*\)",".*".*/\1/p'
    

    Your test string is in file, the output

    Orange
    Swisscom
    Swisscom
    Salt
    Sunrise
    Sunrise
    Sunrise
    Salt
    Free
    SFR
    BYTEL