跳轉到內容

Awk 入門/輸出重定向和管道

來自華夏公益教科書,開放的書籍,開放的世界

輸出重定向運算子

[編輯 | 編輯原始碼]

輸出重定向運算子 ">" 可用於 Awk 輸出語句。例如

   print 3 > "tfile"

—建立一個名為 "tfile" 的檔案,其中包含數字 "3"。如果 "tfile" 已經存在,則其內容將被覆蓋。

如果將更多內容列印到同一個檔案中,其內容將不再被覆蓋。例如,在執行以下程式碼之後

print "How doth the little crocodile" > "poem"
print "    Improve his shining tail," > "poem"
print "And pour the waters of the Nile" > "poem"
print "     On every golden scale!" > "poem"

"poem" 檔案將包含以下內容

How doth the little crocodile 
     Improve his shining tail, 
And pour the waters of the Nile 
     On every golden scale! 

追加重定向運算子

[編輯 | 編輯原始碼]

"追加" 重定向運算子 (">>") 的使用方法與 ">" 相同,不會覆蓋檔案。例如

   print 4 >> "tfile"

—將數字 "4" 追加到 "tfile" 的末尾。如果 "tfile" 不存在,則會建立它並將數字 "4" 追加到它。

將重定向與 printf 一起使用

[編輯 | 編輯原始碼]

輸出和追加重定向也可以與 "printf" 一起使用。例如

   BEGIN {for (x=1; x<=50; ++x) {printf("%3d\n",x) >> "tfile"}}

—將數字 1 到 50 匯出到 "tfile"。

輸出也可以使用 "|" ("管道") 運算子 "管道" 到另一個實用程式。作為一個簡單的例子,我們可以將輸出管道到 "tr" ("轉換") 實用程式以將其轉換為大寫

   print "This is a test!" | "tr [a-z] [A-Z]"

這將產生

   THIS IS A TEST!

關閉檔案

[編輯 | 編輯原始碼]

可以使用函式關閉檔案

close(file)

同時開啟的檔案數量有限制(在 Linux 下,典型限制為 1024),因此您可能希望關閉不再需要的檔案。

注意!如果關閉檔案,然後再次列印到該檔案,系統會將您之前列印的任何內容都擦除,因為它將其視為一個新檔案。例如,在

{
print "How doth the little crocodile" > "poem"
print "    Improve his shining tail," > "poem"
print "And pour the waters of the Nile" > "poem"
print "     On every golden scale!" > "poem"
close("poem")
print "      Lewis Carroll" > "poem"
}

"poem" 檔案將只包含一行

      Lewis Carroll

在關閉檔案後,切勿向其中輸出任何內容!

關閉檔案後,只能追加到其中。

華夏公益教科書