绮鹃�歛wk绯诲垪(14)锛氱粏璇碼wk涓殑鍙橀噺鍜屽彉閲忚祴鍊�


鍥炲埌锛�

  • Linux绯诲垪鏂囩珷
  • Shell绯诲垪鏂囩珷
  • Awk绯诲垪鏂囩珷

awk鍙橀噺

awk鐨勫彉閲忔槸鍔ㄦ�佸彉閲忥紝鍦ㄤ娇鐢ㄦ椂澹版槑銆�

鎵�浠wk鍙橀噺鏈�3绉嶇姸鎬侊細

  • 鏈0鏄庣姸鎬侊細绉颁负untyped绫诲瀷
  • 寮曠敤杩囦絾鏈祴鍊肩姸鎬侊細unassigned绫诲瀷
  • 宸茶祴鍊肩姸鎬�

寮曠敤鏈祴鍊肩殑鍙橀噺锛屽叾榛樿鍒濆鍊间负绌哄瓧绗︿覆鎴栨暟鍊�0銆�

鍦╝wk涓湭澹版槑鐨勫彉閲忕О涓簎ntyped锛屽0鏄庝簡浣嗘湭璧嬪��(鍙寮曠敤浜嗗氨澹版槑浜�)鐨勫彉閲忓叾绫诲瀷涓簎nassigned銆�

gawk 4.2鐗堟彁渚涗簡typeof()鍑芥暟锛屽彲浠ユ祴璇曞彉閲忕殑鏁版嵁绫诲瀷锛屽寘鎷祴璇曞彉閲忔槸鍚﹀0鏄庛��

awk 'BEGIN{
  print(typeof(a))            # untyped
  if(b==0){print(typeof(b))}  # unassigned
}'

闄や簡typeof()锛岃繕鍙互浣跨敤涓嬮潰鐨勬妧宸ц繘琛屾娴嬶細

awk 'BEGIN{
  if(a=="" && a==0){    # 鏈祴鍊兼椂锛屼袱涓兘true
    print "untyped or unassigned"
  } else {
      print "assigned"
  }
}'

鍙橀噺璧嬪��

awk涓殑鍙橀噺璧嬪�艰鍙ヤ篃鍙互鐪嬩綔鏄竴涓�鏈夎繑鍥炲��鐨勮〃杈惧紡銆�

渚嬪锛�a=3璧嬪�煎畬鎴愬悗杩斿洖3锛屽悓鏃跺彉閲廰涔熻璁剧疆涓�3銆�

鍩轰簬杩欎釜鐗圭偣锛屾湁涓ょ偣鐢ㄦ硶锛�

  • 鍙互x=y=z=5锛岀瓑浠蜂簬z=5 y=5 x=5
  • 鍙互灏嗚祴鍊艰鍙ユ斁鍦ㄤ换鎰忓厑璁镐娇鐢ㄨ〃杈惧紡鐨勫湴鏂�
    • x != (y = 1)
    • awk 'BEGIN{print (a=4);print a}'

闂锛�a=1;arr[a+=2] = (a=a+6)鏄�庝箞璧嬪�肩殑锛屽搴斿厓绱犵粨鏋滅瓑浜庯紵arr[3]=7銆備絾涓嶈杩欎箞鍋氾紝鍥犱负涓嶅悓awk鐨勮祴鍊艰鍙ュ乏鍙充袱杈圭殑璇勪及椤哄簭鏈夊彲鑳戒笉鍚屻��

awk涓0鏄庡彉閲忕殑浣嶇疆

  1. 鍦˙EGIN鎴杕ain鎴朎ND浠g爜娈典腑鐩存帴寮曠敤鎴栬祴鍊�
  2. 浣跨敤-v var=val閫夐」锛屽彲瀹氫箟澶氫釜锛屽繀椤绘斁鍦╝wk浠g爜鐨勫墠闈�
    • 瀹冪殑鍙橀噺澹版槑鏃╀簬BEGIN鍧�
    • 鏅�氬彉閲忥細awk -v age=123 'BEGIN{print age}'
    • 浣跨敤shell鍙橀噺璧嬪�硷細awk -v age=$age 'BEGIN{print age}'
  3. 鍦╝wk浠g爜鍚庨潰浣跨敤var=val鍙傛暟
    • 瀹冪殑鍙橀噺澹版槑鍦˙EGIN涔嬪悗
    • awk '{print n}' n=3 a.txt n=4 b.txt
    • awk '{print $1}' FS=' ' a.txt FS=":" /etc/passwd
    • 浣跨敤Shell鍙橀噺璧嬪�硷細awk '{print age}' age=$age a.txt

awk涓娇鐢⊿hell鍙橀噺

瑕佸湪awk涓娇鐢⊿hell鍙橀噺锛屾湁涓夌鏂瑰紡锛�

1.鍦�-v閫夐」涓皢Shell鍙橀噺璧嬪�肩粰awk鍙橀噺

num=$(cat a.txt | wc -l)
awk -v n=$num 'BEGIN{print n}'

-v閫夐」鏄湪awk宸ヤ綔娴佺▼鐨勭涓�闃舵瑙f瀽鐨勶紝鎵�浠�-v閫夐」澹版槑鐨勫彉閲忓湪BEGIN{}銆丒ND{}鍜宮ain浠g爜娈典腑閮借兘鐩存帴浣跨敤銆�

绮鹃�歛wk绯诲垪(14)锛氱粏璇碼wk涓殑鍙橀噺鍜屽彉閲忚祴鍊�_第1张图片

3.鐩存帴鍦╝wk浠g爜閮ㄥ垎鏆撮湶Shell鍙橀噺锛屼氦缁橲hell瑙f瀽杩涜Shell鐨勫彉閲忔浛鎹�

num=$(cat a.txt | wc -l)
awk 'BEGIN{print '"$num"'}'

杩欑鏂瑰紡鏈�鐏垫椿锛屼絾鍙鎬ф渶宸紝鍙兘浼氬嚭鐜板ぇ閲忕殑寮曞彿銆�

你可能感兴趣的:(绮鹃�歛wk绯诲垪(14)锛氱粏璇碼wk涓殑鍙橀噺鍜屽彉閲忚祴鍊�)