在 Linux 中會需要字串處理,學會 cut 指令可以幫助不少

cut

/etc/passwd 中儲存了所有 Linux 帳號的登入資訊,每一行就是一筆資料,欄位有 login name, user id, group id … 等等,並且用 : 分隔

如果想要列出所有使用者的話,可以使用 cut 來辦到

cut 處理的字串是以「行」為單位

root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
cut -d ':' -f 1 /etc/passwd
root
bin
daemon
-d, --delimiter=DELIM
    use DELIM instead of TAB for field delimiter
-f, --fields=LIST
    select only these fields

如果想要其他欄位的話,可以在 -f 參數後面加上

cut -d ':' -f 1,3-4 /etc/passwd
root:0:0
daemon:1:1
bin:2:2

後記

使用 cut 在處理多空格相連的資料時,會比較難判斷是第幾個 fields,應該有其他處理方式