LoginSignup
29
24

More than 3 years have passed since last update.

シェルでASCII制御文字を扱う

Last updated at Posted at 2016-12-09

制御文字の概要

通常は見えない特殊な文字のことを「制御文字」と呼びます。
ASCIIコードの場合は、0番目から31番目、127番目が制御文字です。
ここでは、シェル上で制御文字を扱う方法をまとめます。

制御文字の表現

キャレット記法 8進 10進 16進
^@ 0 0 0
^A 1 1 1
^B 2 2 2
^C 3 3 3
^D 4 4 4
^E 5 5 5
^F 6 6 6
^G 7 7 7
^H 10 8 8
^I 11 9 9
^J 12 10 a
^K 13 11 b
^L 14 12 c
^M 15 13 d
^N 16 14 e
^O 17 15 f
^P 20 16 10
^Q 21 17 11
^R 22 18 12
^S 23 19 13
^T 24 20 14
^U 25 21 15
^V 26 22 16
^W 27 23 17
^X 30 24 18
^Y 31 25 19
^Z 32 26 1a
^[ 33 27 1b
^\ 34 28 1c
^] 35 29 1d
^^ 36 30 1e
^_ 37 31 1f
^? 177 127 7f

制御文字の入力方法

# Ctrl+V Ctrl+A
^A

# Ctrl+V Ctrl+V
^V

制御文字を表示する

catコマンドの場合
# 制御文字は見えない
$cat ctrl.txt
cat2013
horse014
sheep2015
monkey2016

# -vオプションを付与すると制御文字が見える
$cat -v ctrl.txt
cat^A2013
horse^B014
sheep^A2015
monkey^B2016

less, moreコマンドの場合、制御文字は見える
image

エスケープシーケンスと利用例

^Xの表記いろいろ
# 8進表記
$echo $'\030' | more
^X

# 16進表記
$echo $'\x18' | more
^X

# 文字表記
$echo $'\cX' | more
^X
利用例(grep)

# ^A を検索
$cat ctrl.txt | grep $'\cA' | more
cat^A2013
sheep^A2015

# sheep^A を検索
$cat ctrl.txt | grep $'sheep\cA' | more
sheep^A2015
利用例(sed)
# ^B を ^A に置換
$cat ctrl.txt | sed $'s/\x2/\x1/g' | more
cat^A2013
horse^A014
sheep^A2015
monkey^A2016
29
24
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
29
24