Results 1 to 3 of 3
Hello,
I'm trying to use a variable in awk, but can't get it to work. I've researched online, but all the examples I can find point to exactly how I'm ...
- 01-28-2009 #1Just Joined!
- Join Date
- Jan 2009
- Posts
- 7
awk variables
Hello,
I'm trying to use a variable in awk, but can't get it to work. I've researched online, but all the examples I can find point to exactly how I'm doing it. Anyone know what I'm doing wrong here?
It seems like this script should print the same info twice:
However, this is the output:Code:echo "TEST1" awk '/Doctor Ian/' BradsTempFile echo "TEST2" awk -v pat="Doctor Ian" '/pat/' BradsTempFile
Thanks for your help!Code:$ ./TEST TEST1 Doctor Ian - 04 2004 Doctor Ian - 06 2004 TEST2 $
- 01-28-2009 #2Linux Engineer
- Join Date
- Apr 2006
- Location
- Saint Paul, MN, USA / CentOS, Debian, Solaris, SuSE
- Posts
- 1,117
Hi.
How could the same syntax be used for constants and variables? It couldn't. Consider:
Producing:Code:#!/usr/bin/env bash # @(#) s1 Demonstrate awk matching with variable. echo set +o nounset LC_ALL=C ; LANG=C ; export LC_ALL LANG echo "Environment: LC_ALL = $LC_ALL, LANG = $LANG" echo "(Versions displayed with local utility \"version\")" version >/dev/null 2>&1 && version "=o" $(_eat $0 $1) awk set -o nounset echo FILE=${1-data1} echo " Data file $FILE:" cat $FILE echo echo " Results for constant:" awk '/pit/' $FILE PATTERN="pot" echo echo " Results for shell variable (expect failure):" awk -v variable="$PATTERN" "/variable/" $FILE PATTERN="pet" echo echo " Results for shell variable with matching operator:" awk -v variable="$PATTERN" '$0 ~ variable' $FILE exit 0
In addition to experimenting with short awk codes, I usually use Robbins' Effective AWK Programming, possibly available on-line as well as printed, and also O'Reilly's sed & awk.Code:% ./s1 Environment: LC_ALL = C, LANG = C (Versions displayed with local utility "version") OS, ker|rel, machine: Linux, 2.6.11-x1, i686 Distribution : Xandros Desktop 3.0.3 Business GNU bash 2.05b.0 GNU Awk 3.1.4 Data file data1: pat pet pit pot Results for constant: pit Results for shell variable (expect failure): Results for shell variable with matching operator: pet
Best wishes ... cheers, drlWelcome - get the most out of the forum by reading forum basics and guidelines: click here.
90% of questions can be answered by using man pages, Quick Search, Advanced Search, Google search, Wikipedia.
We look forward to helping you with the challenge of the other 10%.
( Mn, 2.6.n, AMD-64 3000+, ASUS A8V Deluxe, 1 GB, SATA + IDE, Matrox G400 AGP )
- 01-28-2009 #3Just Joined!
- Join Date
- Jan 2009
- Posts
- 7
Thanks!!! This is exactly the info I was looking for. Thank you very much!


Reply With Quote