Next| Prev|Index|凡例


B.4 コマンドによるバッファ加工2

英大文字を小文字に変えたり、行のセンタリングを行なう方法について考えます。
1. 大文字・小文字変換
英字の大文字を小文字に変換するには tr(1) コマンドで簡単に実現できます。

いま以下の様なファイルがあったとして、

	Options
	-1   Displays one entry per line.  This is the default when out-
	  put is not to a terminal.
ファイルの先頭で !Gtr A-Z a-z を実行すれば以下の様になります。
(全ての大文字を小文字に変換)
	options
	-1   displays one entry per line.  this is the default when out-
	  put is not to a terminal.
この状態で、さらに 1G!Gtr a-z A-Z を実行すれば全て大文字になります
	OPTIONS                                                            
	-1   DISPLAYS ONE ENTRY PER LINE.  THIS IS THE DEFAULT WHEN OUT- 
	  PUT IS NOT TO A TERMINAL.      

2. センタリング
awk を用いてセンタリングを実行する例を示します。

(解説)
1. 各行の文字数を数え(length($0))
2. 指定した1行の長さとの差の半分を求める( (80 - length($0))/2 )
3. 上記の値だけ空白を付加し、元の行を表示

	1G!Gawk '{for(i=1;i<=(80-length($0))/2;i++) printf " "; print}'
			
					 Options
		-1   Displays one entry per line.  This is the default when out-
			          put is not to a terminal.

3. 空白の圧縮
複数個のスペースを、1つのスペースに置き換えるにはいくつかの方法があります。
ここでは先の tr(1) コマンドを用いた例を解説します。
tr コマンドの -s オプションは連続した文字列1をひとつの文字列2に置き換えます。

tr -s '文字列1' '文字列2'
例えば、先のセンタリング例題で全ての行に tr -s ' ' ' ' を実行すると、以下の結果が得られます。
	1G!Gtr -s ' ' ' '
		
	Options                                                       
	-1 Displays one entry per line. This is the default when out- 
	put is not to a terminal. 	
4. 桁位置での切り出し
行から桁位置を指定し、取り出すには cut(1) コマンドを用います。
-c オプションは桁数を表し、指定した範囲を抽出します
cut -c 開始桁1-終了桁1 [ , 開始桁2-終了桁2...]
この例では、1〜30桁 と 50〜55 桁の文字列を切り出します。
(ただし桁位置が分かるように桁位置を表示してあります。)
	....+....1....+....2....+....3....+....4....+....5....+....6 
	Options                                                       
	-1 Displays one entry per line. This is the default when out- 
	put is not to a terminal. 

	1G!Gcut -c1-30,50-55
		

	....+....1....+....2....+....3....+....4....+....5....+....6 
	Options                                                       
	-1 Displays one entry per linelt when
	put is not to a terminal. 

Next| Prev| Up| Index