Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux基礎 >> 關於Linux

AWK 中如何輸出單引號:三種場景的完整拆解

在 AWK 裡印出單引號是個經典陷阱,因為 AWK 程式本身通常就用單引號包住。要突破這層束縛,得靠「單引號—雙引號—轉義單引號」的交替拼接。

基本串法

規則可以記成:單引號 → 雙引號 → 單引號 → 轉義單引號 → 單引號 → 內容 → 單引號 → 轉義單引號 → 單引號 → 雙引號 → 單引號。其中轉義單引號 \' 就是真正被輸出的那一個。

場景一:輸出字串常數

> echo aaa | awk '{print "select * from A where name='\''TOM'\''"}'
select * from A where name='TOM'

場景二:輸出欄位變數

> echo TOM | awk '{print "select * from A where name='\''"$1"'\''"}'
select * from A where name='TOM'

差別在於把常數位置換成 "$1",也就是先跳出雙引號取得欄位值,再跳回原本的拼接結構。

場景三:輸出環境變數

> key=TOM; echo aaa | awk '{print "select * from A where name='$key"}'
select * from A where name=TOM

> key=TOM; echo aaa | awk '{print "select * from A where name='\''$key'\''"}'
select * from A where name='TOM'

第一條只印出變數值,第二條才會把值用單引號包起來。

其他特殊字元

美元符 $ 與反引號 ` 放在雙引號內即可;反斜線 \ 則需要在前面再加一個反斜線:

echo aaa | awk '{print "$\\`"}'
$`
Copyright © Linux教程網 All Rights Reserved