跳轉到內容

從 Unix 命令列進行即席資料分析/預備知識

來自華夏公益教科書,開放的書籍,開放的世界

在展示命令列示例互動時,將使用這些排版約定

$ command argument1 argument2 argument3 
output line 1 
output line 2 
output line 3 
[...]

$ ” 是 shell 提示符。您鍵入的內容將以粗體顯示;命令輸出以常規型別顯示。

示例資料

[編輯 | 編輯原始碼]

我將在示例中使用以下示例檔案。

Unix 密碼檔案

[編輯 | 編輯原始碼]

密碼檔案可以在 /etc/passwd 中找到。系統上的每個使用者在該檔案中都有一行(記錄)。每個記錄都有七個欄位,用冒號(':')字元分隔。這些欄位是使用者名稱、加密密碼、使用者 ID、預設組、gecos、主目錄和預設 shell。我們可以使用 head 命令檢視前幾行,該命令只打印檔案的頭幾行。相應地,tail 命令只打印最後幾行。

$ head -5 /etc/passwd 
root:x:0:0:root:/:/bin/bash 
bin:x:1:1:bin:/bin:/sbin/nologin 
daemon:x:2:2:daemon:/sbin:/sbin/nologin 
adm:x:3:4:adm:/var/adm:/sbin/nologin 
lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin

人口普查資料

[編輯 | 編輯原始碼]

美國人口普查局在 其網站上釋出了公共使用微資料樣本 (PUMS)。我們將使用華盛頓州資料的 1% 樣本,檔案 pums_53.dat,可以從 這裡下載。

$ head -2 pums_53.dat 
H000011715349 53010 99979997 70 15872 639800 120020103814700280300000300409 
02040201010103020 0 0 014000000100001000 0100650020 0 0 0 0 0000 0 0 0 0 0 
05000000000004400000000010 76703521100000002640000000000
P00001170100001401000010420010110000010147030400100012005003202200000 005301000
000300530 53079 53 7602 76002020202020202200000400000000000000010005 30 53010
70 9997 99970101006100200000001047904431M 701049-20116010 520460000000001800000
00000000000000000000000000000000000000001800000018000208

重要說明:此資料檔案的格式在可從 這裡下載的 Excel 電子表格中進行了描述。

開發人員效率與計算機效率

[編輯 | 編輯原始碼]

這裡討論的技術在開發人員時間方面通常非常高效,但在計算資源(CPU、I/O、記憶體)方面通常效率較低。這種蠻力和無知可能不優雅,但當您還不瞭解問題的範圍時,通常最好花 30 秒編寫一個執行 3 小時的程式,而不是反過來。

線上手冊

[編輯 | 編輯原始碼]

"man" 命令顯示有關給定命令的資訊(俗稱命令的“手冊頁”)。線上手冊頁是非常寶貴的資源;如果您對這裡介紹的命令進行任何嚴肅的工作,最終您會從頭到尾閱讀所有手冊頁。在 Unix 文件中,命令(或函式、或檔案)的手冊頁通常稱為 command(n)。數字“n”指定手冊的某個部分,以消除存在於多個部分中的條目的歧義。因此,passwd(1) 是 passwd 命令的手冊頁,passwd(5) 是 passwd 檔案的手冊頁。在 Linux 系統上,您可以透過將部分號作為第一個引數給出,如“man 5 passwd”來請求手冊的特定部分。以下是 man 命令對自己的說法

$ man man 
man(1)                                                        man(1) 
NAME
       man - format and display the on-line manual pages 
       manpath - determine user's search path for man pages 

SYNOPSIS 
       man [-acdfFhkKtwW] [--path] [-m system] [-p string] [-C 
       config_file] [-M pathlist] [-P pager] [-S section_list] 
       [section] name ... 

DESCRIPTION 
       man formats and displays the on-line manual pages. If you 
       specify section, man only looks in that section of the 
       manual. name is normally the name of the manual page, 
       which is typically the name of a command, function, or 
       file. [...]

標準輸入、標準輸出、重定向和管道

華夏公益教科書