Search code examples
awkconcatenationpipe

How do I print the pipe character in awk


This is the code I've written, it works:

awk "BEGIN{print int(($high-32)*5/9)  int(($low-32)*5/9)}";

Results in: 1911

I would like to the '19' and '11' seperated by " | " so that the output looks like this: 19 | 11

I have tried to insert " \| " both as a literal and a var but both resulted in errors. Haven't seen much in the various forums. What am I missing? Thanks.


Solution

  • Assuming you're on a Unix system you should be using single quotes rather than double around your script (see https://mywiki.wooledge.org/Quotes), and using awk variables rather than allowing shell variables to expand to become part of the body of your awk script (see How do I use shell variables in an awk script?), e.g.:

    awk -v high="$high" -v low="$low" 'BEGIN{print int((high-32)*5/9)  int((low-32)*5/9)}'
    

    and then the enhancement you're asking for would be:

    awk -v high="$high" -v low="$low" -v OFS=' | ' 'BEGIN{print int((high-32)*5/9), int((low-32)*5/9)}'
    

    or if you prefer:

    awk -v high="$high" -v low="$low" 'BEGIN{print int((high-32)*5/9) " | " int((low-32)*5/9)}'