Linux:cutコマンドで表示カラム(フィールド)を指定する方法

スポンサーリンク

cutコマンドで表示カラム(フィールド)を指定する方法

cutコマンドで表示カラム(フィールド)を指定するには-fオプションを指定します。

 

オプションの説明

  -d, --delimiter=DELIM   use DELIM instead of TAB for field delimiter
  -f, --fields=LIST       select only these fields;  also print any line
                            that contains no delimiter character, unless
                            the -s option is specified

 

以下のテキストを処理するとします。

$ cat test.txt
id,lower,upper
1,a,A
2,b,B
3,c,C
4,d,D

 

-fオプションを指定した場合(-dはデリミタを指定するオプション)

$ cut -d, -f2 test.txt
lower
a
b
c

$ # 複数指定
$ cut -d, -f1,3 test.txt
id,upper
1,A
2,B
3,C

$ # 出力はフィールドの番号順
$ cut -d, -f3,1 test.txt
id,upper
1,A
2,B
3,C

$ # 範囲指定
$ cut -d, -f1-3 test.txt
id,lower,upper
1,a,A
2,b,B
3,c,C

$ # 最後まで
$ cut -d, -f2- test.txt
lower,upper
a,A
b,B
c,C

$ # 最初から
$ cut -d, -f-2 test.txt
id,lower
1,a
2,b
3,c

 

-fオプションを指定しない場合

$ cut -d, test.txt
cut: you must specify a list of bytes, characters, or fields
Try 'cut --help' for more information.