Linuxのコマンドラインのテキスト操作テクニックのインスタンス共有
わずかな学習コストを投入するだけで大きな価値のリターンを得る技術は少ない。正規表現はこのような技術に属している。残念なことに、多くの人がパスワードのような文法形式に頭を下げられ、ドアに入ることさえできなかった。
どうして正規表現を学ぶべきですか。一つは、実践の中でこの技術を応用するのは難しくなく、数少ない数のメタ文字と複雑ではない文法と理解すれば、強力なテキスト操作能力を得ることができる。二つ目は、正規表現がテキストを処理する最も簡単で最も効率的な解決方法を提供することが多い(場合によっては唯一の解法かもしれない)。複雑な状況に遭遇して、もしあなたが正規表現ができないならば、手の施しようがなくて、暗然として神傷するしかありません。
正規表現は入門は簡単だが、精通は難しい。本稿ではこのタスクに挑戦するつもりはありません^^
テキスト検索 コードのコピー> man grep | col -b > grephelp.txt
コードのコピー
> grep "find" grephelp.txt
To find all occurrences of the word `patricia' in a file:
To find all occurrences of the pattern `.Pp' at the beginning of a line:
To find all lines in a file which do not contain the words `foo' or
コードのコピー
> grep --color "find" grephelp.txt
コードのコピー
> grep -H -n --color "find" grephelp.txt
grephelp.txt:252: To find all occurrences of the word `patricia' in a file: grephelp.txt:256: To find all occurrences of the pattern `.Pp' at the beginning of a line:grephelp.txt:265: To find all lines in a file which do not contain the words `foo' or
コードのコピー
> grep -A 2 -B 2 -H -n --color "find" grephelp.txtgrephelp.txt-250-
grephelp.txt-251-EXAMPLES
grephelp.txt:252: To find all occurrences of the word `patricia' in a file:
grephelp.txt-253-
grephelp.txt-254- $ grep 'patricia' myfile
--
-- grephelp.txt-254- $ grep 'patricia' myfilegrephelp.txt-255-
grephelp.txt:256: To find all occurrences of the pattern `.Pp' at the beginning of a line:
grephelp.txt-257-
grephelp.txt-258- $ grep '^\.Pp' myfile
--
--
grephelp.txt-263- match any character.
grephelp.txt-264-
grephelp.txt:265: To find all lines in a file which do not contain the words `foo' or
grephelp.txt-266- `bar':
grephelp.txt-267-
grepには2つの変異体,egrepとfgrepがある。基本正規モード(BREs)のみをサポートするgrepに比べて、egrepは拡張正規モード(EREs)をサポートするため、検索能力がより強い。fgrepは、正規モードが完全にサポートされていないため、3つのツールの中で最も高速です。
テキスト置換
コードのコピー
> cat grephelp.txt | tr '[:lower:]' '[:upper:]'
[:alnum:]:アルファベット
[:alpha:]:アルファベット
[:cntrl:]:制御文字
[:digit:]:数値
[:graph:]:グラフィック文字
[:lower:]:小文字
[:print:]:印刷可能文字
[:punct:]:句読点
[:space:]:空白文字
[:upper:]:大文字
[:xdigit:]:16進数
trコマンドの適用シーンは非常に制限されており、より柔軟なモード置換を行うにはsed(stream editor、ストリームエディタ)もあります。