Search code examples
awkquotation-marks

Shell script - proper quoting in the awk command


I have a awk command with 2 parameters and one condition - if it is fullfilled, it returns second parameter. So far, it looks like this and works well

awk -v PARAM_NAME="user" '{ if ($1 == "\""PARAM_NAME"\":") { print $2;}}'

Now, I would like to add one check and see if the second parameter ends with a certain character. I know that, in order to read the last character of $2, I need to read it like this.

echo "${2: -1}"

The problem is - I dont know how to escape those double quetes properly (or at least thats where I think the problem lies). This is what I have now, could someone tell me what is wrong with it? Thank you

awk -v PARAM_NAME="user" '{ if ($1 == "\""PARAM_NAME"\":" && "${2: -1}" == "\"","\"") { print $2;}}'

Whole command

cf env some-odata-app | grep "\"hana\":" -A 30 | awk -v PARAM_NAME="user" -v lastchar="${2: -1}" '{ if ($1 == "\""PARAM_NAME"\":" && lastchar == ",") { print substr($2, 2, length($2)-3);}}'

Expected input after first two commands. I want to get both password and user, cleared from quotes. So need to know if to cut two or three characters from the end

"hana": [
   {
    "binding_name": null,
    "credentials": {  
     "password": "obfuscated",
     "schema": "oiuhjoiuhyupoihj",
     "url": "pkpokpokp[kjpo[kpo",
     "user": "USER"
    },
 
  ]

Solution

  • The gist of the question appears to have changed from 'passing shell parameters into awk' to 'pulling last character from a awk variable/field' to 'parsing out the user and password from a cf/grep command batch'.

    Sample data generated by the cf/grep command batch:

    $ cat hana.dat
    "hana": [
       {
        "binding_name": null,
        "credentials": {  
         "password": "obfuscated",
         "schema": "oiuhjoiuhyupoihj",
         "url": "pkpokpokp[kjpo[kpo",
         "user": "USER"
        },
       ]
    

    OP wants to run 2 separate commands, one to extract the user and one to extract the password.

    One awk solution that uses the double quote as the input field separator:

    $ awk -F'"' -v PARAM_NAME="user" '$2 == PARAM_NAME { print $4 }' hana.dat
    USER
    $ awk -F'"' -v PARAM_NAME="password" '$2 == PARAM_NAME { print $4 }' hana.dat
    obfuscated
    

    Keep in mind we can also pull both values via a single awk call, eg:

    $ awk -F'"' '$2 == "password" || $2 == "user" {print $4}' hana.dat
    obfuscated
    USER
    

    One grep/cut idea that emulates the awk solution:

    $ grep -E 'password|user' hana.dat | cut -d'"' -f4
    obfuscated
    USER
    

    NOTE: Will likely need to reformat the output depending on how OP plans to capture and use these values.