awk 中 FS的用法


在openwrt文件 ar71xx.sh中

查詢設備類型時,有這么一句,

machine=$(awk 'BEGIN{FS="[ \t]+:[ \t]"} /machine/ {print $2}' /proc/cpuinfo)
解決:
1)查看cpuinfo
root@hbg:/dev# cat  /proc/cpuinfo
system type             : Qualcomm Atheros QCA9533 rev 2
machine                 : Atheros AP143 reference board
processor               : 0
cpu model               : MIPS 24Kc V7.4
BogoMIPS                : 432.53
wait instruction        : yes
microsecond timers      : yes
tlb_entries             : 16
extra interrupt vector  : yes
hardware watchpoint     : yes, count: 4, address/irw mask: [0x0000, 0x0ff8, 0x0ff8, 0x0ff8]
isa                     : mips1 mips2 mips32r1 mips32r2
ASEs implemented        : mips16
shadow register sets    : 1
kscratch registers      : 0
core                    : 0
VCED exceptions         : not available
VCEI exceptions         : not available
2)awk截取信息, FS為指定格式; 以 “:” 冒號為分界符,兩邊都是制表符"\t",第二個參數
   /machine指定了以machine為開始的那一行
  
所以命令的結果是:
Atheros AP143 reference board  

 

==============================================

補充知識:

awk中常見的內建變量(Built-in Variables)

NF( Number of Fields ) : awk 讀入一行數據的字段數,通俗地說,就是一行數據被划分成了幾段?便於對各字段進行遍歷
NR( Number of Records ) : awk 已讀入的行數,相當於一個計數器。
RS( Record Separator ) : 行分隔符。awk從文件上讀取資料時, 將根據 RS 的定義把資料切割成許多Records,awk一次僅讀入一個Record,以進行處理。預設值是'\n'
FS( Field Separator ) : 列分割符。決定了怎么將一行划分為幾段。預設值是 空白符(空白和Tab)
FILENAME : awk 正在處理的數據文件名

例如:

創建一個 data.txt的文件,內如如下:(共3行,其中第三行為空)

a:b   c:d    123

w:q   d:e    234

 

執行命令:

 

hbg@root:~/dl/test$ awk 'BEGIN{FS="[ :]+"}{print $0, $1, NR, NF}' data.txt
a:b c:d 123 a 1 5
q:w d:e 234 q 2 5
  3 0
hbg@root:~/dl/test$ awk 'BEGIN{FS="[ :]+"}{print $0}' data.txt       // 打印所有數據
a:b c:d 123
q:w d:e 234

 

hbg@root:~/dl/test$ awk 'BEGIN{FS="[ :]+"}{print $1}' data.txt      // 打印分隔符的第一列
a
q

 

hbg@root:~/dl/test$ awk 'BEGIN{FS="[ :]+"}{print $2}' data.txt      // 打印分隔符的第二列
b
w

 

hbg@root:~/dl/test$ awk 'BEGIN{FS="[ :]+"}{print NR}' data.txt     // 打印行號
1
2
3
hbg@root:~/dl/test$ awk 'BEGIN{FS="[ :]+"}{print NF}' data.txt    // 段數(一行被分成了幾段)
5
5
0
hbg@root:~/dl/test$

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM