Help us understand the problem. What is going on with this article?

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

制御文字の概要

通常は見えない特殊な文字のことを「制御文字」と呼びます。
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
rtakasuke
よろしくね!
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした