get a string/phrase with awk from 1 line

Viewed 67

We are using a script which it returns as a result the following

<env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/"><env:Header/><env:Body><consultaDeudaResponse xmlns="http://www.example.org/webServicesvc-schema-services"><estado>120007</estado><mensaje>CONSULTA DE DEUDA CORRECTA.</mensaje><deudas><deuda><N>0</nisRad><secNis>1</secNis><nombre>TEST</nombre></env:Envelope> I'm trying to get from awk the phrase that says CONSULTA DE DEUDA CORRECTA, as you can see everything is in just one line, no spaces or comma. So I got no idea how to get that phrase and set it up in a variable.

I used

const=$(awk '/CONSULTA DE DEUDA CORRECTA/ ' output)

and

const=$(awk '/^CONSULTA DE DEUDA CORRECTA/ ' output)

But either the whole phrase comes together with the rest of the info I dont need, or the variable is empty.

Any help appreciated.

2 Answers

Since this is a simple substitution on a single string it's a better candidate for a sed script than an awk script:

$ sed -n 's:.*<mensaje>\(.*\)</mensaje>.*:\1:p' file
CONSULTA DE DEUDA CORRECTA.

$ const=$(sed -n 's:.*<mensaje>\(.*\)</mensaje>.*:\1:p' file)
$ echo "$const"
CONSULTA DE DEUDA CORRECTA.

If you really want to use awk though then with GNU awk for the 3rd arg to match():

$ awk 'match($0,"<mensaje>(.*)</mensaje>",a){print a[1]}' file
CONSULTA DE DEUDA CORRECTA.

Could you please try following. Written on mobile so couldn't test it should work though.

awk '
match($0,/<mensaje>.*<\/mensaje>){
  print substr($0,RSTART+9,RLENGTH-19)
}' Input_file

Or in one liner form use:

var=$(awk 'match($0,/<mensaje>.*<\/mensaje>){print substr($0,RSTART+9,RLENGTH-19)}' Input_file)

Related