print
items >
output-file
This redirection prints the items into the output file named output-file. The file name output-file can be any expression. Its value is changed to a string and then used as a file name (see Expressions).When this type of redirection is used, the output-file is erased before the first output is written to it. Subsequent writes to the same output-file do not erase output-file, but append to it. (This is different from how you use redirections in shell scripts.) If output-file does not exist, it is created. For example, here is how an awk program can write a list of BBS names to one file named name-list, and a list of phone numbers to another file named phone-list:
$ awk '{ print $2 > "phone-list"
> print $1 > "name-list" }' BBS-list
$ cat phone-list
-| 555-5553
-| 555-3412
...
$ cat name-list
-| aardvark
-| alpo-net
...
Each output file contains one name or number per line.
print
items >>
output-file
This redirection prints the items into the pre-existing output file named output-file. The difference between this and the single-‘>’ redirection is that the old contents (if any) of output-file are not erased. Instead, the awk output is appended to the file. If output-file does not exist, then it is created.
Here is the example code:
cat > test.txt
a
b
c
d
awk 'BEGIN{print "e1" >> "test.txt"; print "e2" >> "test.txt"; print "e3" >> "test.txt";}'
$ cat test.txt
a
b
c
d
e1
e2
e3
awk 'BEGIN{print "e1" > "test.txt"; print "e2" > "test.txt"; print "e3" > "test.txt";}'
But I just don't understand why the test.txt is gone in code below:
awk 'BEGIN{print "e1" > "test.txt"; system("rm test.txt");print "e2" > "test.txt"; print "e3" > "test.txt";}'
No comments:
Post a Comment