上QQ阅读APP看书,第一时间看更新
Shell quotes with AWK
As you have seen, we will be using the command line for most of our short AWK programs. The best way to use it is by enclosing the entire program in single quotes, as follows:
$ awk '/ search pattern / { awk commands }' inputfile1 inputfile2
When you are working on a shell, it is good to have a basic understanding of shell quoting rules. The following rules apply only to the POSIX-compliant, GNU Bourne Again Shell:
- Quoted and non-quoted items can be concatenated together. The same is true for quoted and non-quoted item concatenation. For example:
$ echo "Welcome to " Learning "awk"
>>>
Welcome to Learning awk
- If you precede any character with a backslash (\) in double quotes, the shell removes the backslash on execution and treats subsequent characters as literal without having any special meaning:
$ echo "Apple are \$10 a dozen"
>>>
Apple are $10 a dozen
- Single quotes prevent shell expansions of the command and variable. Anything between the opening and closing quotes is not interpreted by the shell, it is passed as such to the command with which it is used:
$ echo 'Apple are $10 a dozen'
>>>
Apple are $10 a dozen
It is impossible to embed a single quote inside single-quoted text.
- Double quotes allow variable and command substitution. The $ , ` , \, and " characters have special meanings on the shell, and must be preceded by a backslash within double quotes if they are to be passed on as literal to the program:
$ echo "Hi, \" Jack \" "
>>>
Hi, "Jack"
- Here is an AWK example with single and double quotes:
$ awk 'BEGIN { print "Hello world" }'
It can be performed as follows:
$ awk "BEGIN { print \"Hello world \" }"
- Both give the same output:
Hello world
Sometimes, dealing with single quotes or double quotes becomes confusing. In these instances, you can use octal escape sequences. For example:
- Printing single quotes within double quotes:
$ awk "BEGIN { print \"single quote' \" }"
- Printing single quotes within single quotes:
$ awk 'BEGIN { print "single quote'\'' " }'
- Printing single quotes within single quotes using the octal escape sequence:
$ awk 'BEGIN { print "single quote\47" }'
- Printing single quotes using the command-line variable assignment:
$ awk -v q="'" 'BEGIN { print "single quote"q }'
- All of the preceding AWK program executions give the following output:
single quote'