LoginSignup
0
0

More than 3 years have passed since last update.

Linuxでファイルの指定された列を表示する方法(awk)

Posted at

Linuxのコマンドawkを使用して、ファイルの指定された列を表示することができます。

環境

  • OS:CentOS Linux release 8.1.1911
[demo@centos8 ~]$ cat /etc/redhat-release
CentOS Linux release 8.1.1911 (Core)
[demo@centos8 ~]$

1. 半角スペース区切りの指定された列を表示する方法

半角スペース区切りの以下のファイル(b01.txt)があります。

b01.txt
1 a ab
2 bb bcd
3 ccc cdef
4 dddd defgh
5 eeeee efghij

以下のコマンドで2列目のみ表示することができます。

awk '{print $2}' b01.txt

実行結果
[demo@centos8 test]$ awk '{print $2}' b01.txt
a
bb
ccc
dddd
eeeee
[demo@centos8 test]$

2. 「,」区切りの指定された列を表示する方法

「,」区切りの以下のファイル(b02.txt)があります。

b02.txt
1,a,ab
2,bb,bcd
3,ccc,cdef
4,dddd,defgh
5,eeeee,efghij

以下のコマンドで2列目のみ表示することができます。

awk -F',' '{print $2}' b02.txt

実行結果
[demo@centos8 test]$ awk -F',' '{print $2}' b02.txt
a
bb
ccc
dddd
eeeee
[demo@centos8 test]$

3. タブ区切りの指定された列を表示する方法

タブ区切りの以下のファイル(b03.txt)があります。

b03.txt
1   a   ab
2   bb  bcd
3   ccc cdef
4   dddd    defgh
5   eeeee   efghij

以下のコマンドで2列目のみ表示することができます。

awk -F'\t' '{print $2}' b03.txt

実行結果
[demo@centos8 test]$ awk -F'\t' '{print $2}' b03.txt
a
bb
ccc
dddd
eeeee
[demo@centos8 test]$

4. 指定された行列を表示する方法

半角スペース区切りの以下のファイル(b01.txt)があります。

b01.txt
1 a ab
2 bb bcd
3 ccc cdef
4 dddd defgh
5 eeeee efghij

以下のコマンドで3行目2列目を表示することができます。

awk 'NR==3 {print $2}' b01.txt

実行結果
[demo@centos8 test]$ awk 'NR==3 {print $2}' b01.txt
ccc
[demo@centos8 test]$

sedコマンドと組み合わせた以下のコマンドでも3行目2列目を表示することができます。

sed -n 3p b01.txt | awk '{print $2}'

実行結果
[demo@centos8 test]$ sed -n 3p b01.txt | awk '{print $2}'
ccc
[demo@centos8 test]$

以上

0
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
0
0