2

this is what I've tried (and a few other iterations). snippet from file

APOLLO_KEY=service:abcd
cat packages/graph/.env | gawk '{ if ($0 = "APOLLO_KEY" ) { RS = "=" } ; { print $1 } }'

it returns APOLLO_KEY instead of the value for each row in the file. the value I would expect and want to get is

service:abcd

I get that there are considerable issues with parsing the file this way. I'm just doing it for some one off commands, and at this point am frustrated with my awk knowledge/googling.

xenoterracide
  • 59,188
  • 74
  • 187
  • 252
  • If it's a file with environment variables, then it's possible that the file has multi-line valued variables, no? It's furthermore unclear whether you're interested in the value of the APOLLO_KEY variable specifically (which would be available as $APOLLO_KEY after sourcing the file), or whether you want to see all values for all variable names. – Kusalananda Aug 13 '20 at 16:27
  • @Kusalananda it does not, I'm just doing this for some one off scripting not worrying about perfect parsing, but now I'm frustrated with the fact that I can't get this awk right. I only want to see the one, but I'm not trying to import it into my shell. – xenoterracide Aug 13 '20 at 16:28
  • This should illustrate the issue: gawk '{ if ($0 = "SOMETHING RANDOM" ) { print } }' – terdon Aug 13 '20 at 16:54
  • Indeed there are. https://unix.stackexchange.com/a/433245/5132 – JdeBP Aug 13 '20 at 19:25

2 Answers2

4
gawk '{ if ($0 = "APOLLO_KEY" ) { RS = "=" } ; { print $1 } }'

$0 = "APOLLO_KEY" would assign the string to $0, comparison is ==. I don't think you want to change the record separator RS here, but the field separator FS (and you need to do that with -F or -vFS= on the command line, so it works before awk splits the line). Also, no need to use an explicit if statement here, we just put the condition on the whole code block.

Assuming simplistic data (and definitely not something using the full shell syntax!) this should work:

awk -F= '$1 == "APOLLO_KEY" { print $2 }'

Note that this breaks if the value contains = signs, since it only takes the second field on the line.

If you need to deal with values like that, one solution would be to manually remove everything up to the first =. We might as well pass the field name outside the code to make it a bit cleaner:

awk -v key=APOLLO_KEY -F= '$1 == key { sub(/^[^=]+=/, ""); print }'
ilkkachu
  • 138,973
  • Or sed -n '/^FOO=/s///p' or just sed -n 's/^FOO=//p', both of which would not bother about what characters are used in the value. Neither would support multi-line values though. – Kusalananda Aug 13 '20 at 16:57
0

awk -F "=" '{for(i=1;i<=NF;i++){if($i ~ /APOLLO_KEY/)print $(i+1)}}' filename

output

service:abcd
Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255