LoginSignup
1
0

More than 1 year has passed since last update.

cutコマンド備忘録(ちょっとだけawk)

Posted at

はじめに

Linuxのcutコマンドのオプションを度々忘れてしまうので復習&備忘録。。

<サンプルコード>

$ cat list_fruit
01:apple,りんご:120円 aomori
02:orange,オレンジ:100円 ehime
03:banana,バナナ:95円 miyazaki

文字数を指定して切り取りたい

1〜2文字目までを切り取る。

$ cut -c 1,2 list_fruit
01
02
03

1〜12文字目までを切り取る。

$ cut -c 1-12 list_fruit
01:apple,りんご
02:orange,オレ
03:banana,バナ

12文字目以降を切り取る。

$ cut -c 12- list_fruit
ご:120円 aomori
レンジ:100円 ehime
ナナ:95円 miyazaki

ある特定の文字で区切りたいとき

$ cut -d <区切り文字> -f <項目数> ファイル名

注) -dと-f はセットで使う必要がある。

カンマで区切られた1番目のフィールドを切り出す。

$ cut -d ',' -f 1 list_fruit
01:apple
02:orange
03:banana

スペースで区切られた1番目のフィールドを切り出す。

$ cut -d ' ' -f 1 list_fruit
01:apple,りんご:120円
02:orange,オレンジ:100円
03:banana,バナナ:95円

スペースで区切られた2番目のフィールドを切り出す。

$ cut -d ' ' -f 2 list_fruit
aomori
ehime
miyazaki

番外編

ふと思ったのだが、複数の区切り文字を使いたい時は、どうするんだ。。
例えば、apple, orange, bananaの部分だけを取り出したい時。
もちろん文字数が違うから-cでは指定できない。
-d-fを使って、:,の間を複数の区切り文字を使って指定したい。。

調査した結果、cutコマンドでは複数の区切り文字は使えない!
→awkコマンドを使えば可能!

awk -F'[区切り文字]' '{print $表示したい項目}'

↓これでapple達が取れる。

$ awk -F'[:,]' '{print $2}' list_fruit
apple
orange
banana

ちなみにprint $1をやってみるとこんな感じ

$ awk -F'[:,]' '{print $1}' list_fruit
01
02
03
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0