1 de 99

シェルスクリプト言語論

第6回 (2019-05-23)

https://richlab.org/j/2352

金沢大学総合メディア基盤センター�大野浩之�ユニバーサルシェルプログラミング研究所�松浦智之

このスライドのPDF⇒ https://richlab.org/j/2d62

1

2 de 99

ShellScript Programming

#6 (2019-05-23)

https://richlab.org/j/2352

Information Media Center, Kanazawa Univ.�Hiroyuki Ohno, Ph.D.�Universal Shell Programming Lab.�Tomoyuki Matsuura

You can get this slide from https://richlab.org/j/2d62

2

3 de 99

第6回概要(2019-05-23)

  • POSIX準拠(=高互換性,長期持続性実現)のための準備 ― 標準語話者になる
    • 到達目標
      • 実在するUNIX系OSには様々な方言(引数・動作の違い)があることを知る
      • 文法、コマンド、正規表現、それぞれの方言にどんなものがあるのかを知る
      • 「どの実装にも通用する範囲で書く」という配慮を身に付ける
      • どこまでが標準語でどこからが方言なのか、判断する方法を知る
    • (1/3)シェル文法の方言と対策 ― 20年本第1章
      • 変数、制御構文(if/case等)、ロケール、環境変数の初期化、他…
    • (2/3)各コマンドの方言と対策 ― 20年本第2章
      • echo、AWK、sed、grep、date、他...
    • (3/3)正規表現の方言と対策 ― 20年本第3章
      • 3種類の正規表現(BREとERE、AWKの正規表現)
      • POSIXの各コマンドはどの正規表現に対応しているか
      • BRE、ERE、AWKの正規表現の各論
    • 発展 ― 方言か標準語かの認識のしかた

3

4 de 99

Overview of #6(2019-05-23)

  • Preparation for POSIX Centric ― To be a standard language speaker
    • Goal
      • Learn the fact that there are many dialects (differences) among Unix-like OSs.
      • Learn the kinds of dialects, shell sentences and syntax, commands, regexp
      • Be careful to write programs without dialects as possible
      • Learn whether the word is a dialects or not
    • (1/3) Counterplan for dialects on UNIX shell syntax
      • variables, constructions (if, case, …), locale, environment variables, and so forth
    • (2/3) Counterplan for dialects on basic UNIX commands
      • echo, AWK, sed, grep, date, and so forth
    • (3/3) Counterplan for dialects on Regular Expressions
      • 3 types of Regular Expressions (“BRE”, “ERE” and AWK’s ERE subset)
      • Learn which RE type each POSIX command supports.
      • Details about BRE, ERE, AWK’s ERE
    • Study -- How do we distinguish between a dialect or common language on UNIX?

4

5 de 99

1.ソフトウェアにおける

「標準語」とは

5

6 de 99

  • “Standard Language”

on software

6

7 de 99

シェル・プログラミングへの不満

7

このあいだ、僕の書いたシェルスクリプトを、友達のパソコンで動かそうとしたら、動かなくてさあ。

シェルスクリプトは、環境依存っていうの?入っているOSによって動かないことが多いんだよね。

そうそう。Linuxで書いた

シェルスクリプトを

FreeBSDに持っていったら動かないし……。

8 de 99

Typical complaints against ShellSctipt

8

A while ago, I brought my ShellScript to my friend’s computer. But it didn’t work.

Is that “platform-dependency?”�Another OS doesn’t often allow to work ShellScripts my OS allows.

Yes.

The ShellScript I made for Linux didn’t work on FreeBSD.

9 de 99

シェル・プログラミングへの不満

9

いやいや、

そもそも呼び出すコマンドが

あったりなかったりするから。

それに同じコマンドあっても、

OSによって

通用しないオプションあるし…

bashならbash、というふうに

使うシェルを決めて、

全ての環境にインストールすれば?

10 de 99

Typical complaints against ShellSctipt

10

But really, not only shell but also various commands aren’t available on each platforms.

The available options are also different even if the same command exists as well.

Hey, why don’t you install the same shell, bash or zsh, on all the computers which you are going to use.

11 de 99

シェル・プログラミングへの不満

11

表示(フォーマット)が

違うこともあるよね。

psコマンドとか。

正規表現で使える文字

(メタ文字)もOSごとに

なんかバラバラだしさ

12 de 99

Typical complaints against ShellSctipt

12

In “ps” command case, the display format are also different among each OSs.

You know, Regular Expression rule is slightly different, too.

13 de 99

シェル・プログラミングへの不満

13

PerlとかRuby、Pythonとかの方が絶対いいよ。

だよね。

言語が決まれば、使える関数とか文法、書式が

きっちり決まるからね。

大抵どこのOSにもあるから

標準語みたいなものでしょ!

14 de 99

Typical complaints against ShellSctipt

14

PHP, Ruby, Python are more useful definitly.

Yeah!

It’s promissed that the same language gives the same behaviours.

Those are almost like standard languages because they could be installed on almost all of OSs.

15 de 99

「標準語」の誤解

  • それはぜんぜん違う!
    • Perl、Ruby、Python、……�などは、どんなに普及していても「標準語」ではない。

15

16 de 99

Misunderstanding of “standard language”

  • That isn’t right at all!
    • Java, Perl, PHP, Ruby, Python, ……�They can’t be standard languages no matter how they become popular.

16

17 de 99

「標準語」の誤解

  • 標準語とそうでないもの

違いは何か?

17

標準語

そうでない

HTML

Flash

FTP

Windowsファイル共有、AppleTalk

C言語、 C++、 C#

Java、 アセンブリ

18 de 99

Misunderstanding of “standard language”

  • Standard language vs. not

What’s the different point?

18

Standard Language

not std.

HTML

Flash

FTP

Windowsファイル共有、 AppleTalk

C言語、 C++、 C#

Java、 アセンブリ

19 de 99

「標準語」の誤解

  • 一人(一社)が所有・支配しているものは�標準語ではない。
    • その人の意向で、使い方のルールが�変わってしまう恐れがある。�⇒話者(ユーザー)が翻弄される
    • いざという時の代替品がない。�⇒サポート終了や欠陥発覚で、話者(ユーザー)の� 逃げ道がなくなる。

19

イラスト: 素材Good

ほら、困るでしょ!!

20 de 99

Misunderstanding of “standard language”

  • The one which is owned by only one�organization is not a standard language.
    • The specification could be changed by just�the organization’s convenience.�⇒The users will be swayed by the convenience.
    • There is also no alternatives.�⇒What do you do when any vulnerability is discovered,� or the organization finish supporting the software?

20

Illustrated by “sozai-good”

Be careful!

21 de 99

「標準語」の誤解

一製品に依存し、替えられない状態を「ロックイン」と呼ぶ。(⇒検索)�

21

標準語でないもの

その理由

Linux

  • 「優しい終身の独裁者」(Linus氏)が仕様を最終決定

FreeBSDなどのOS

  • それを作っているのが一団体しかいない

Perlなどの言語

bashなどのシェル

GNU版AWK,sed�など(GNU版コマンド群)

22 de 99

Misunderstanding of “standard language”

This feature is call “vendor lock-in” or “customer lock-in.”�

22

Non-std-lang.

Reason

Linux

  • The “Benevolent director for life” (Linus Torvalds) decides its spec finally.

OSs (FreeBSD, …)

  • There is only one organization which is developing it.

Perl, Ruby, …, etc

Shells (bash, …)

GNU commands

23 de 99

でもこれはセーフ

23

標準語として

認められるもの

理由

Linux, FreeBSDなどの�POSIX準拠部分

  • 複数の団体が相当するものを実装していて、代替品が存在する。

bash, ksh, zshなどの�POSIX準拠部分

GNU版AWK,sedなど�GNUコマンドの�POSIX準拠部分

24 de 99

Misunderstanding of “standard language” (safe case)

24

The safe as a std-lang.

Reason

The part of following POSIX on UNIX-liks OSs

  • 2 or more organizations develop the imprements which have the same functions.

The part of following POSIX on Bourne’s extended shells (bash, ksh, zsh, ...)

The part of following POSIX on GNU commands

25 de 99

「標準語」の誤解

  • 「標準語」とは何か?
    • ある地域に暮らす一般的な人々が、当然のものとして認識可能な言語。
  • では、ソフトウェアにおける「標準語」とは?
    • あるプラットフォーム(例:UNIX)を使う一般的なユーザが、当然のものとして使用可能な規格やプログラミング言語。
    • あるプラットフォーム(例:UNIX)に準拠した一般的な環境で、当然のものとして動作するプログラム。

25

26 de 99

Misunderstanding of “standard language” (safe case)

  • What is “standard language”?
    • A language that common people living in a certain area can recognize as natural.
  • So, what is “standard language” on software?
    • Standards and programming languages that common users who use one platform (e.g. UNIX) can use as a matter of course.
    • A program that operates as a matter of course in a general environment conforming to a platform (e.g. UNIX).

26

27 de 99

2.標準語を話そう

27

28 de 99

2. Be a standard language speaker

28

29 de 99

2.1. 方言を知る

29

30 de 99

2.1. Know which is a dialect

30

31 de 99

方言を知る

  • まず「方言」(=通用しない)と知るのが重要

31

32 de 99

Know which is a dialect

  • Important whether the word is a dialect or not

32

33 de 99

方言を知る

  • POSIX中心主義で注意する三種類の方言
    • シェルの文法
    • コマンドの種類・動作
    • 正規表現

33

34 de 99

Know which is a dialect

  • 3 categories of dialect on Shell Programming
    • Sentence structure and Syntax on each ShellScripts
    • Difference in specifications of the same named commands
    • Types of Regular Expressions supported by each commands

34

35 de 99

2.2. シェルスクリプトの文法にある方言

35

36 de 99

2.2. Dialects of ShellScripts

36

37 de 99

bashというシェルについて

  • UNIXのシェルには様々な種類がある。
    • sh (Bourneシェルと呼ばれ、最低限の機能を持つ)
    • ash, bash, dash, fish, ksh, zsh, … (上記の拡張)
    • csh, tcsh (Cシェルと呼ばれる別系統のもの)
  • bashは、普及率が高い
    • 多くのLinuxディストリビューションで採用
    • macOSも採用
    • その他多くのOSでも、パッケージとして存在

37

38 de 99

A kind of shell “bash”

  • There are many shells on UNIX
    • sh (Called “Bourne shell”, which has the minimum functions as UNIX shell.)
    • ash, bash, dash, fish, ksh, zsh, … (Expansions of the above)
    • csh, tcsh (Another shell family, it called “C shell”)
  • bash has a large share.
    • Most of Linux distributions adopt it.
    • Also macOS
    • Most of the other OSs prepare the install package for bash.

38

39 de 99

bashにはいろいろ便利な独自機能がある

  • ブレース展開 ― “{x..x}”

39

$ bash

$ echo {1..9}

1 2 3 4 5 6 7 8 9

$ echo {1..9}x{1..9}

1x1 1x2 1x3 1x4 1x5 1x6 1x7 1x8 1x9 2x1 2x2 ... 9x9

$ exit

$ dash

$ echo {1..9}

{1..9}

$ echo {1..9}x{1..9}

{1..9}x{1..9}

$

40 de 99

Bash has many original functions

  • Brace expansion “{x..x}”

40

$ bash

$ echo {1..9}

1 2 3 4 5 6 7 8 9

$ echo {1..9}x{1..9}

1x1 1x2 1x3 1x4 1x5 1x6 1x7 1x8 1x9 2x1 2x2 ... 9x9

$ exit

$ dash

$ echo {1..9}

{1..9}

$ echo {1..9}x{1..9}

{1..9}x{1..9}

$

41 de 99

bashにはいろいろ便利な独自機能がある

  • プロセス置換 ― “<( コマンド )

41

$ bash

$ diff /etc/passwd <(tail -n +2 /etc/passwd)

1d0

< root:x:0:0:root:/root:/bin/bash

$ exit

$ dash

$ diff /etc/passwd <(tail -n +2 /etc/passwd)

dash: Syntax error: “(“ unexpected

$

42 de 99

Bash has many original functions

  • Process replacing ― “<( command )

42

$ bash

$ diff /etc/passwd <(tail -n +2 /etc/passwd)

1d0

< root:x:0:0:root:/root:/bin/bash

$ exit

$ dash

$ diff /etc/passwd <(tail -n +2 /etc/passwd)

dash: Syntax error: “(“ unexpected

$

43 de 99

bashにはいろいろ便利な独自機能がある

  • PIPESTATUS ― パイプで繋がれた全コマンドの戻り値

43

$ bash

$ exit 10 | exit 20 | exit

$ echo retval:$? retvals:${PIPESTATUS[@]}

retval:0 retvals:10 20 0

$ exit

$ dash

$ exit 10 | exit 20 | exit

$ echo retval:$? retvals:${PIPESTATUS[@]}

dash: Syntax error: Bad substitution

$

44 de 99

Bash has many original functions

  • PIPESTATUS ― It has all return-values all the pipelined commands gave.

44

$ bash

$ exit 10 | exit 20 | exit

$ echo retval:$? retvals:${PIPESTATUS[@]}

retval:0 retvals:10 20 0

$ exit

$ dash

$ exit 10 | exit 20 | exit

$ echo retval:$? retvals:${PIPESTATUS[@]}

dash: Syntax error: Bad substitution

$

45 de 99

bashにはいろいろ便利な独自機能がある

  • 「え、それ、独自機能だったの!?」
    • 自然言語で方言と知った時のショックに似ている?
  • 「使えないとは何と不便な!」
    • 使えば便利。�だが「ロックイン」という不便さで跳ね返ってくる。

45

46 de 99

Bash has many original functions

  • That function has been a dialect one!?
    • Do you have any similar episode about English?
  • What is inconvenient not to use them.
    • The function are certainly convenient but...�you have to accept “vendor lock-in” if you use them.

46

47 de 99

【演習】逆に、bashの方が不便なこともある

  • まずは次のコードを打ち込んで保存zshtest.sh
    • 引数をつけたり、つけなかったりして実行

47

#!/bin/zsh

if [ "_$1" = '_' ]; then

# 何もしない

else

echo "引数に$1が設定されました"

fi

48 de 99

[exercise] Know worse case of bash than the other shells

  • Save the following shellscript as “zshtest.sh
    • Next, run it with/without an argument.

48

#!/bin/zsh

if [ "_$1" = '_' ]; then

# Do nothing

else

echo "$1 was set as the first argument."

fi

49 de 99

【演習】逆に、bashの方が不便なこともある

  • zshをbashに替えて保存bashtest.sh
    • 同じように実行したらどうなるか、確かめよ。

49

#!/bin/bash

if [ "_$1" = '_' ]; then

# 何もしない

else

echo "引数に$1が設定されました"

fi

50 de 99

[exercise] Know worse case of bash than the other shells

  • Replace the “bash” in the 1st line with “zsh” and save as “bashtest.sh
    • And run it and compare their behaviours.

50

#!/bin/bash

if [ "_$1" = '_' ]; then

# Do nothing

else

echo "$1 was set as the first argument."

fi

51 de 99

【演習】逆に、bashの方が不便なこともある

  • bashでは、ifやcase文で「何もしない」は不可
    • 「何もしない」という意味のコード“:”を�便宜的に追加しなければならない。

51

#!/bin/bash

if [ "_$1" = '_' ]; then

# 何もしない

:

else

echo "引数に$1が設定されました"

fi

これが必要

52 de 99

[exercise] Know worse case of bash than the other shells

  • Prohibited comment-only in if/case sentences on bash
    • In this case, you have to use a dummy command “:”�(It means non-operation)

52

#!/bin/bash

if [ "_$1" = '_' ]; then

# Do nothing

:

else

echo "$1 was set as the first argument."

fi

Required!

53 de 99

POSIX中心主義における注意点

  • 最大公約数的な記述を心掛ける
    • bashなど、一部のシェルでしかできない機能は�使わない
    • bashなど、一部のシェルでは動かないコードは�書かない

53

54 de 99

Importance for POSIX Centric programming

  • Be careful not to use non-standard functions
    • Don’t use non-standard functions which are supported on only some OSs.
    • Don’t use any special sentence structure which are supported on only some OSs.

54

55 de 99

2.3. コマンドにある方言

55

56 de 99

2.3. Dialect on commands

56

57 de 99

そもそも、OSによって存在しないコマンドがある

  • Linuxにしかない or なかった
    • readlink シンボリックリンクの元ファイルを調べる)
    • seq (数字を列挙する)
    • tac (ファイルを下の行から表示する、"cat"の逆)
  • FreeBSD等のBSD系やMacにしかない
    • jot (数字を列挙する、seqのBSD版)
  • そもそもPOSIXではない(実際にAIX等にはない)
    • mktemp (一時ファイルを作る)
    • which (指定されたコマンドの置かれている絶対パスを求める)

などなど……

57

58 de 99

There are original cmds which isn’t supported by the other OSs

  • Supported by only Linux
    • readlink print resolved symbolic links or canonical file names
    • seq print a sequence of numbers
    • tac concatenate and print files in reverse
  • Supported by only BSD
    • jot print sequential or random data
  • Supported by only PC-UNIX
    • mktemp create a temporary file or directory
    • which locate a program file in the user's path

etc…...

58

59 de 99

そもそも、OSによって存在しないコマンドがある

  • POSIXに存在しないコマンドは、使わない
    • 存在の有無は、�POSIXの公式ページで都度確認
  • 無くて不便ならば、自作する。
    • あるいは作ってあるものを使う。�https://github.com/ShellShoccar-jpn/misc-tools
    • でも自作すると勉強になる。

59

POSIX文書が閲覧できるページ

60 de 99

There are original cmds which isn’t supported by the other OSs

  • Don’t use the command which referred on the POSIX document
  • Or make a command you want by yourself
    • or you may use the command we made.https://github.com/ShellShoccar-jpn/misc-tools
    • However, it’s meaningful to make them�by yourself!

60

POSIX document page

61 de 99

方言が強いコマンド その1 ― date

  • Linux、BSD・Mac系のものは日時計算が可能
    • 今から4週間前は?(Linuxの人)date --date '4 weeks ago'
    • 今から4週間前は?(BSD・Mac系の人)date -v-4w
      • BSD・Mac系は、起点を今以外にもできる

せっかくできるのに書式が違う!

  • そもそもPOSIXには無い機能
    • 無くて不便だから追加された。
    • でも各自が勝手に追加したので、他で通用しない「方言」になってしまった。

※ 無いと不便な日時計算を行う方法は、今後の講義で解説。

61

62 de 99

A tight dialect command (1) - date

  • date commands on Linux, BSDs, Mac support timewise calculation
    • “4 months ago from now?” (on Linux)date --date '4 weeks ago'
    • “4 months ago from now?” (BSDs, Mac)date -v-4w
      • BSDs & Mac can also calculate it instead of from now.

Both implement are possible but they have incompatible usages.

  • However, none of them are supported by POSIX
    • The above OSs added them because POSIX didn’t support it yet.
    • However, those made the date commands uncompatible.

※ A compatible command we made will be introduced #8 of this lecture.

62

63 de 99

方言が強いコマンド その2 ― tr

  • man文書から英数字を全部消す例(記号だけ残す)

    • System V系では後者でないと動かない。
    • POSIX準拠OSでは、後者にすると記号"[","]"まで消える

63

  • BSD系と、それを採用したPOSIX準拠OSの場合

$ zcat /usr/share/man/man1/tr.1.gz | head | tr -d '0-9A-Za-z'

  • System V系(Solarisなど)の場合

$ zcat /usr/share/man/man1/tr.1.gz | head | tr -d '[0-9][A-Z][a-z]'

64 de 99

A tight dialect command (2) ― tr

  • Example to remove all alphabets from man docs

    • System V OSs require the latter usage.
    • But “[”,“]” will be removed on BSD/POSIX with the latter

64

  • In case of BSD and POSIX compatible OSs

$ zcat /usr/share/man/man1/tr.1.gz | head | tr -d '0-9A-Za-z'

  • In case of System V (Solaris)

$ zcat /usr/share/man/man1/tr.1.gz | head | tr -d '[0-9][A-Z][a-z]'

65 de 99

方言が強いコマンド その2 ― tr

  • 歴史的事情によりPOSIXでも解決できなかった
    • POSIXのtrコマンドのmanページ�でも言及している。
    • ごく稀なケース
    • POSIX中心主義ではtrコマンドで�“x-y”という記述を使わない。
      • tr -d ’0-9’ (代替案1)→ tr -d ’0123456789’(代替案2)→ sed ’s/[0-9]//g’

65

66 de 99

A tight dialect command (2) ― tr

  • Wasn’t be able to resolve the incompatible problem in spite of POSIX
    • tr man page on POSIX also�mentions it.
    • But it’s a very rare case.
    • Not to use “x-y” usage of tr�command on POSIX Centric prog.
      • tr -d ’0-9’ (Replacement 1) --> tr -d ’0123456789’(Replacement 2) --> sed ’s/[0-9]//g’

66

67 de 99

方言が強いコマンド その3 ― GNU版コマンド群

  • 独自拡張が様々施されている
    • Linuxにあるのコマンドの多数
    • bashも実はGNU製
    • コマンド名 --version”を�実行すれば確認できる
    • 便利なオプションが、独自に多数追加されている。
    • Linux JM(Linuxの日本語man)と、POSIXのmanを見比べ、POSIXには記述があるかどうか確認すべき

67

68 de 99

A tight dialect command (3) ― GNU commands

  • There are various extensions
    • Most of Linux distributions have
    • bash is also one of GNU
    • You can confirm by “--version” opt�to know this is a GNU product.
    • Various convenient functions are available.
    • You can find them by comparing Linux man page and POSIX man.

68

69 de 99

方言が強いコマンド その3 ― GNU製コマンド群

見比べるとPOSIXに無いオプションや機能が多数

69

70 de 99

A tight dialect command (3) ― GNU commands

You can know how many original functions GNU commands have.

70

71 de 99

【演習】挙動が異なるコマンド

  • 次のコマンドを実行し、周囲の人と�互いに結果を比べてみよ
    • 今日の年月日を求め、数字の出現回数のランキングをとる。

71

$ date +%Y%m%d | sed 's/./&_/g' | tr _ '\n' | sort | uni�q -c | sort -r

72 de 99

[exercise] Experience differences of command behaviours

  • Run the following one-liner and compare with other student’s results.
    • This one-liner is to count the number of each numbers of the date.

72

$ date +%Y%m%d | sed 's/./&_/g' | tr _ '\n' | sort | uni�q -c | sort -r

73 de 99

挙動が異なるコマンド

  • 結果 ― どこが違う?

73

$ date +%Y%m%d …

2 6

2 2

2 0

1 5

1 1

1

$

$ date +%Y%m%d …

2 6

2 2

2 0

1 5

1 1

1

$

FreeBSD

CentOS

74 de 99

[exercise] Experience differences of command behaviours

  • Can you see these difference?

74

$ date +%Y%m%d …

2 6

2 2

2 0

1 5

1 1

1

$

$ date +%Y%m%d …

2 6

2 2

2 0

1 5

1 1

1

$

on FreeBSD

on CentOS

75 de 99

挙動が異なるコマンド

  • 結果 ― 字下げ(インデント)文字数が違う!

75

$ date +%Y%m%d …

2 6

2 2

2 0

1 5

1 1

1

$

$ date +%Y%m%d …

2 6

2 2

2 0

1 5

1 1

1

$

76 de 99

[exercise] Experience differences of command behaviours

  • Every depth of the indent are different!

76

$ date +%Y%m%d …

2 6

2 2

2 0

1 5

1 1

1

$

$ date +%Y%m%d …

2 6

2 2

2 0

1 5

1 1

1

$

77 de 99

挙動が異なるコマンド

  • uniqコマンドの“-c”による字下げ数は未定義
    • POSIXでは未定義なので、各OSが決める。
    • このように、POSIXには詳細仕様を規定しきれていない箇所があるので注意。
    • wcコマンドでも同様のことが起こる

77

78 de 99

[exercise] Experience differences of command behaviours

  • Because the depth by uniq “-c” is undefined on POSIX
    • There are some ambiguous specifications in spite of POSIX.
    • Each OS vendor decide the undefined spec in detail because they can’t help them.
    • wc command also has the same problem.

78

79 de 99

参考ページ

  • どの環境でも使えるシェルスクリプトを書くためのメモ
    • POSIX中心主義に従う上での、�文法とコマンドの注意点のまとめ
    • 新たに注意点が発見されたら、�随時更新している。
  • すべてのUNIXで20年動くプログラムはどう書くべきか
    • 上記を含め、書籍化したもの。

79

80 de 99

See also

  • Note to make completely compatible ShellScripts
    • The page is a checking list to�comply with POSIX
    • I update it whenever I discover�what we have to be careful about�POSIX compliant.
    • (However, in Japanese)

80

81 de 99

2.4. 正規表現にある方言

81

82 de 99

2.4. Dialects of Regular Expressions

82

83 de 99

正規表現とは?

  • 文字列に見られる特徴を、記号化したもの。
    • 例:
      • 先頭に,数字3つ,ハイフン記号,数字4つ,それで最後
      • ^[0-9]{3}-[0-9]{4}$
      • → 日本の郵便番号の特徴を表現している
  • 共通の特徴を持つ文字列を検索・抽出・置換するのに便利

83

84 de 99

What is Regular Expression (RE) ?

  • A method to symbolize the features strings have
    • example:
      • From the top, 3-digit, hyphen, 4-digit, That’s all
      • ^[0-9]{3}-[0-9]{4}$
      • → It is expressed the feature Japanese zip codes have.
  • It’s useful to search or replace the strings which have the same features.

84

85 de 99

正規表現(Regular Expression)にも方言がある

  • POSIXにあるもの(標準語
    • BRE (Basic RE:基本正規表現)
    • ERE (Extended RE:拡張正規表現)
    • AWKの方言 (EREの機能限定版)
  • その他
    • Perlの正規表現(PCRE: Perl Compatible RE)
    • JavaScriptの正規表現
    • GNUコマンドの正規表現            など

※ 「その他」はどれもEREの拡張になっている

※ EREはBREの完全な上位互換ではない

85

86 de 99

There are some types on Regular Expressions

  • POSIX supporting
    • BRE (Basic Regular Expression)
    • ERE (Extended Regular Expression)
    • AWK’s dialect (ERE subset)
  • Non-POSIX
    • Perl Extension(PCRE: Perl Compatible Regular Expression)
    • JavaScript Extension
    • GNU Extension etc.

※ All Non-POSIXs is based on ERE

※ ERE is not completely an upward compatible with BRE!

86

87 de 99

覚えるべき正規表現の種類は2(+1)種類

  • POSIXにあるもの(標準語
    • BRE (Basic RE:基本正規表現)
    • ERE (Extended RE:拡張正規表現)
    • AWKの方言 (EREの機能限定版)
  • その他
    • Perlの正規表現(PCRE: Perl Compatible RE)
    • JavaScriptの正規表現
    • GNUコマンドの正規表現            など

「その他」はどれもEREの拡張なので後でもよいし、POSIXにはない

87

88 de 99

You have to learn the only 3 types!

  • POSIX certified
    • BRE (Basic Regular Expression)
    • ERE (Extended Regular Expression)
    • AWK’s dialect (ERE subset)
  • Others
    • Perl Extension (PCRE: Perl Compatible Regular Expression)
    • JavaScript Extension
    • GNU Extension      etc.

“Others” are unnecessary as long as we program with only POSIX commands.

88

89 de 99

後は、どのコマンドがどれに対応しているか覚えるだけ

  • AWKは「AWKの方言」
  • Extendedの“E”がついている“egrep”と“grep -E”はERE
  • その他は全てBRE

89

コマンド名

対応しているもの

コマンド名

対応しているもの

AWK

AWKの方言

grep (“-E”あり)

ERE

ed

BRE

more

BRE

egrep

ERE

sed

BRE

ex

BRE

vi

BRE

grep (“-E”なし)

BRE

90 de 99

Next, you have to learn which command supports which RE

  • AWK’s dialect means ERE-subset by AWK.
  • “grep -E” supports ERE, while “grep” supports BRE.
  • All other commands support BRE.

90

Command

Supporting type

Command

Supporting type

AWK

AWK’s dialect

grep (with “-E” opt.)

ERE

ed

BRE

more

BRE

egrep

ERE

sed

BRE

ex

BRE

vi

BRE

grep (w/o “-E” opt.)

BRE

91 de 99

BRE、ERE、AWKの方言の詳細

  • 長いので省略 ⇒ 次のページを読むこと
    • どのUNIXコマンドでも使える正規表現
    • POSIX中心主義に従う上での、正規表現の注意点のまとめ

91

92 de 99

See also

  • See the following page for details.

92

93 de 99

方言を検証するためのソフト

  • これらのソフト、追加インストールしました?
    • dash zsh
    • bash LinuxmacOSの人は入っているので入れなくてよい)
    • nawk または mawkLinuxの人のみ)
    • gawk gsed macOSFreeBSD系の人のみ)
    • coreutils macOSFreeBSD系の人のみ)
  • 無ければインストール
    • Ubuntu系の人は“apt”コマンド、RedHat系の人は“yum”コマンド
    • Mac OS Xの人は“brew”、“installer”、“port”コマンドなど
    • FreeBSDの人は“pkg”コマンド

93

94 de 99

The software to experience various dialects

  • Are you already install the followings?
    • dash and zsh
    • bash (Linux and macOS users must already be installed)
    • nawk or mawk (for only Linux users)
    • gawk gsed (for only macOS or *BSD users)
    • coreutils (for only macOS or *BSD users)
  • Install them if not yet
    • Ubuntu family OS users can use “apt” command.
    • RedHat family OS users can use “yum” command.
    • macOS OS users can use “brew”/“installer”/“port” command.
    • FreeBSD users can use “pkg” command.

94

95 de 99

3.本日の宿題

95

96 de 99

3. Assignment

96

97 de 99

正規表現の使い方を覚える

  • 「文字列」の部分に次の文字列を与えた時だけ、表示(grepの場合)、置換(sedの場合)する正規表現を�それぞれについて考えよ。
    • 電話番号 例: 090-1234-5678
    • URL 例: https://example.com/?q=hogehoge
    • メールアドレス 例: president@office.example.com

97

$ echo 文字列 | grep 解答となる正規表現

$ echo 文字列 | grep -E 解答となる正規表現

$ echo 文字列 | sed ’s/解答となる正規表現/~/g’

98 de 99

Exercise of Regular Expression

  • Answer each REs for grep and sed when the following kinds of string are given as the “string.”
    • Phone No. e.g. 090-1234-5678
    • URL e.g. https://example.com/?q=hogehoge
    • e-mail address e.g. president@office.example.com

98

$ echo string | grep your RE

$ echo string | grep -E your RE

$ echo string | sed ’s/your RE/~/g’

99 de 99

講義スライド案内 ― Lecture Slide Index

  • Previous
    • #5 https://richlab.org/j/2562
  • Next
    • #7 https://richlab.org/j/2e62

99