導論與複習

Bash 指令稿入門

Alex Scriven

Data Scientist

課程導覽

本課程將涵蓋:

  • 從命令列轉為 Bash 指令稿
  • Bash 指令稿中的變數與資料型別
  • 控制敘述
  • 函式與指令稿自動化
Bash 指令稿入門

為什麼用 Bash 指令稿?(Bash)

先來想想為什麼用 Bash?

  • Bash 是「Bourne Again Shell」(語帶雙關)

  • 80 年代開發,但至今仍很普及。是許多 Unix 系統與 Mac 的預設 shell

  • Unix 撐起網際網路!(執行 ML 模型、資料管線)

    • AWS、Google、Microsoft 都提供產品的 CLI
Bash 指令稿入門

為什麼用 Bash 指令稿?(指令稿!)

那為什麼要寫 Bash 指令稿?

  • 執行 shell 指令更省事(不用每次都複製貼上!)
  • 具備強大的程式設計結構
Bash 指令稿入門

預期基礎知識

 

本課程預期你具備一些基礎。

  • 瞭解命令列(terminal、shell)是什麼
  • 用過 catgrepsed 等基本指令

如果有點生疏也別擔心——我們現在就來複習!

Bash 指令稿入門

Shell 指令複習

幾個重要的 shell 指令:

  • (e)grep 依 regex 模式比對來過濾輸入
  • cat 逐行串接檔案內容
  • tailhead 只輸出最後或最前的 -n(旗標)行
  • wc 統計字數或行數(搭配 -w-l 旗標)
  • sed 依模式進行字串取代
Bash 指令稿入門

REGEX 提醒

「Regex」或正規表示式是 Bash 指令稿的關鍵技能。

你常會需要過濾檔案、檔內資料、比對引數等多種用途。很值得複習一下。

要測試 regex,你可以用像 regex101.com 這類好用的網站

Bash 指令稿入門

Shell 小練習

用例子來複習一些 shell 指令。

有一個 fruits.txt 文字檔,包含 3 行資料:

banana
apple
carrot

若執行 grep 'a' fruits.txt,會得到:

banana
apple
carrot
Bash 指令稿入門

Shell 小練習

但如果執行 grep 'p' fruits.txt,會得到:

apple

回想一下,中括號可指定一組待比對字元,如 [eyfv]。搭配 ^ 則變成反向集合(排除這些字母/數字)。

因此執行 grep '[pc]' fruits.txt 會得到:

apple
carrot
Bash 指令稿入門

Shell 小練習

你大概用過終端機中的「pipe」。如果檔案裡有很多水果名稱,可以用 sort | uniq -c

  • 前者依字母排序,後者計數
  • 若想要前 n 名,接著再 pipe 到 wc -l 並用 head
cat new_fruits.txt | sort | uniq -c | head -n 3
  14 apple
  13 bannana
  12 carrot
Bash 指令稿入門

一起來練習吧!

Bash 指令稿入門

Preparing Video For Download...