When it comes to command line text processing, from an abstract point of view, there are three major pillars



Download 125.91 Kb.
Page34/60
Date09.03.2023
Size125.91 Kb.
#60849
1   ...   30   31   32   33   34   35   36   37   ...   60
Learn GNU AWK

ENVIRON


To access environment variables of the shell, you can call the special array variable ENVIRON with the name of the environment variable as a string key.
$ # existing environment variable $ # output shown here is for my machine, would differ for you $ awk 'BEGIN{print ENVIRON["HOME"]}' /home/learnbyexample $ awk 'BEGIN{print ENVIRON["SHELL"]}' /bin/bash $ # defined along with awk command $ # note that the variable is placed before awk $ word='hello' awk 'BEGIN{print ENVIRON["word"]}' hello
ENVIRON is a good way to get around awk's interpretation of escape sequences. This is especially helpful for fixed string matching, see index section for examples.
$ s='hi\nbye' $ # when passed via -v option $ awk -v ip="$s" 'BEGIN{print ip}' hi bye $ # when passed as an environment variable $ ip="$s" awk 'BEGIN{print ENVIRON["ip"]}' hi\nbye
Here's another example when a regexp is passed to an awk command.
$ # when passed via -v option $ r='\Bpar\B' $ awk -v rgx="$r" '$0 ~ rgx' word_anchors.txt awk: warning: escape sequence `\B' treated as plain `B' $ r='\\Bpar\\B' $ awk -v rgx="$r" '$0 ~ rgx' word_anchors.txt apparent effort two spare computers $ # when passed as an environment variable $ r='\Bpar\B' $ rgx="$r" awk '$0 ~ ENVIRON["rgx"]' word_anchors.txt apparent effort two spare computers

Summary


This short chapter revisited the -v command line option and introduced the ENVIRON special array. These are particularly useful when the awk command is part of a shell script. More about arrays will be discussed in later chapters.
The next chapter will cover control structures.

Exercises


a) Use contents of s variable to display all matching lines from the input file sample.txt. Assume that the s variable doesn't have any regexp metacharacters and construct a solution such that only whole words are matched.
$ s='do' $ ##### add your solution here Just do-it
b) Replace all occurrences of o for the input file addr.txt with literal contents of s variable. Assume that the s variable has regexp metacharacters.
$ s='\&/' $ ##### add your solution here Hell\&/ W\&/rld H\&/w are y\&/u This game is g\&/\&/d T\&/day is sunny 12345 Y\&/u are funny

Download 125.91 Kb.

Share with your friends:
1   ...   30   31   32   33   34   35   36   37   ...   60




The database is protected by copyright ©ininet.org 2024
send message

    Main page