text2:
3 Chicago
5 Los Angeles
1 Boston
4 Atlantic
script_1:
#! /bin/bash
awk '{
print $0 > "text";
}
END {
close(text);
#clear buffer, making sure buffer content(4 lines of
#records from text2) are saved in "text" file
system("sort < text");
#Run the external command, return code of system is
#the return code of external command. And standard
#output and standard error of external command are
#as awk. In this case, awk standard output is terminal
#So it will output content to terminal
}' text2
#output:
#1 Boston
#3 Chicago
#4 Atlantic
#5 Los Angeles
#Following awk program is same as above, unless
#that, we define standard output of awk to text3
#Then system's external command will output to
#text3
awk '{
print $0 > "text";
}
END {
close(text);
system("sort < text");
}' text2 >text3
cat text3;
#output:
#1 Boston
#3 Chicago
#4 Atlantic
#5 Los Angeles
2. Run the external command with pipeline
script_1:
#! /bin/bash
awk 'BEGIN {
shell="/bin/bash"
command="echo Hello world!";
print command | shell;
print "======="
command="v=\"Amazing world!\"";
print command | shell;
print "======="
command="echo $v";
print command | shell;
close(shell);
}'
#output:
#=======
#=======
#Hello world!
#Amazing world!
# For all commands we passed to shell, it never get
# executed until call "close". That's why 2 lines of
# separators get output firstly, then shell's output
# get printed out lastly.
# Before "close" command is called, all commands we
# passed to shell will be buffered, and these commands
# will get executed like a script when close is called.
awk 'BEGIN {
command="v=\"Hello world!\"";
shell="/bin/bash";
print command | shell;
close(shell);
command="echo $v";
print command | shell;
close(shell);
}'
#output: empty line
#Since we closed the shell after feeding command to it.
#Then next time, when print feed command to the shell,
#awk starts a new shell process, who doesn't recognize
#the variable "v" at all! Apparently it will output an
#empty line, since v is empty there.
No comments:
Post a Comment