說明表明您的腳本檔案將使用以下命令在我們的系統上進行測試:
awk -f ./awk4.awk input.csv
編寫一個 awk 腳本,該腳本將接受以下文件並輸出姓名和成績字段
顯然,我創建了一個 bash 腳本,它需要是一個 awk 腳本,可以從命令列使用 awk -f 運行。下面是我的程式碼。有沒有一種簡單的方法可以將 bash 腳本轉換為 awk 腳本而無需重做所有內容?對方向真的很困惑。
#!/usr/bin/awk -f
##comment create an awk script that will accept the following file and output the name and grade fields
##comment specify the delimiter as ","
awk -F, '
/./ {
##comment print the name and grade, which is first two fields
print $1" "$2
}' $1
答案1
在 awk 腳本中,內容是您將awk
作為命令提供的內容。所以在這種情況下,那就是:
/./ {
##comment print the name and grade, which is first two fields
print $1" "$2
}
然而,這會讓使用-F ,
so 而不是在區塊FS
中設定變得很棘手BEGIN
。
所以你的腳本將是:
#!/usr/bin/awk -f
##comment create an awk script that will accept the following file and output the name and grade fields
##comment specify the delimiter as ","
BEGIN { FS = "," }
/./ {
##comment print the name and grade, which is first two fields
print $1" "$2
}
答案2
你已經寫了一個awk
腳本,但是把它放在了一個腳本中。這是你的awk
腳本:
/./ {
##comment print the name and grade, which is first two fields
print $1" "$2
}
將其保存到文件中script.awk
並運行
awk -F',' -f script.awk inputfile
現在對您的腳本有一些提示:
awk
命令看起來像CONDITION {COMMAND(S)}
.如果CONDITION
滿足一行(記錄),{COMMAND(S)}
則執行。如果不存在CONDITION
,{COMMAND(S)}
則對所有記錄執行,如果不存在則只要滿足{COMMAND(S)}
就列印該記錄 。CONDITION
在你的情況下:
/./
是一個與任何字元相符的正則表達式...所以除了空行之外的所有行 - 作為一個條件,它幾乎是多餘的您用作
" "
變數之間的分隔符,用於,
應用預設值您需要
,
在腳本的初始區塊中提供 using 作為分隔符號BEGIN
。
BEGIN {FS=","}
{print $1,$2}
如果您也想使用逗號作為輸出分隔符,請使用:
BEGIN {FS=OFS=","}
{print $1,$2}
答案3
awk 腳本只是可由awk
. awk 腳本有兩種編寫方法:
只需將 awk 命令寫入文本文件並使用
awk -f /path/to/file.awk
.在你的情況下,那就是:/./ { ##comment print the name and grade, which is first two fields print $1" "$2 }
你可以將其運行為:
awk -F, -f /path/to/file.awk inputFile
或者,如果您需要僅使用 運行它
awk -f ./path/to/file.awk inputFile
,而不使用-F,
則在腳本本身中設定欄位分隔符號:BEGIN{ FS=","} /./ { ##comment print the name and grade, which is first two fields print $1" "$2 }
然後運行
awk -f /path/to/file.awk inputFile
。編寫命令,但使用 shebang 指定哪個解釋器應該讀取腳本。在你的情況下,看起來像這樣:
#!/usr/bin/awk -f ## With this approach, you can't use -F so you need to set ## the field separator in a BEGIN{} block. BEGIN{ FS=","} /./ { ##comment print the name and grade, which is first two fields print $1" "$2 }
然後你可以使腳本可執行(
chmod a+x /path/to/file.awk
)並像這樣運行它:/path/to/file.awk inputFile
這些都是 awk 腳本。第三個選項是寫一個殼腳本,並讓 shell 腳本運行 awk。那看起來像這樣:
#!/bin/sh
awk -F, '
/./ {
##comment print the name and grade, which is first two fields
print $1" "$2
}' "$1"
你所擁有的既不是一件事,也不是另一件事:你使用的是 awk shebang,但有一個 shell 腳本而不是 awk 腳本。