sedコマンドの使い方

sedコマンドで、複数の変換処理の指定をする

cat file |
 sed -e "s/OldText1/NewText1/g" \
     -e "s/OldText1/NewText1/g" |
 while read LINE
 do
  ...
 done

デリミタを / から変更する

 s%abc/ef%ABC-EF%g

文字列の変換

 sed -e "s/OldText/NewText/g" 

sedコマンドsはsubstitute、gはgloballyの略。

行頭の文字列を消す

 sed -e "s/^TextToRemove//"

行末の文字列を消す

 sed -e "s/TextToRemove\$//"

$はシェルの特殊文字なので、sedより先に解釈させてはいけない。
そこで \ を $ の前につけて、エスケープする必要がある。

文字列を追加する

 sed -e "s/abc/abcxyz/g"
 sed -e "s/^/TextToInsert/"
 sed -e "s/\$/TextToAppend/g"

文字列の追加は、任意の場所を指定することはできない。
するなら、行頭か行末を指定して、置換する。

ドットとアスタリスク

 sed -s "s/.*/abcd/"

括弧内の文字列を削除する

$ cat file 
0123456
abc(abc)jkl
mn(123)qrstp

$ sed -e "s/(.*)/()/" file
0123456
abc()jkl
mn()qrstp
$ 

idコマンドからユーザIDを取り出す

$ id | sed -e 's/uid=//' -e 's/(.*//'
1000
$ 

idコマンドからユーザ名を取り出す

$ id | sed 's/uid=.*(\(.*\)) gid=.*/\1/'
harue
$ 

括弧そのものを表す際は、そのままエスケープせずに()で良い。
グループ化する際の括弧は\(\)のようにエスケープする。

PATTERN以降を全て削除する

#!/bin/bash

STRING=abc/def/ghi
PATTERN=/
STRING=`echo "$STRING" | sed -e "s%$PATTERN.*%%"`
echo $STRING #=> abc

指定した位置から、ある文字数分を切り取る

$ STRING=abcdef
$ echo "$STRING" | cut -c1-5
abcde
$ 
  • c1-5(開始位置と長さ)を変数にすると、以下のようになる。
#!/bin/bash

STRING=abcdef
FIRST=1
LEN=5
echo $STRING | cut -c$FIRST-$LEN

awkを使って、ファイルの先頭から5文字だけを取り出す

$ awk '{printf "%-.5s\n", $0}' < file
abced
abc
abced
abce
abced
abced
$ 

%-.5s の部分は、先頭から最大5文字を取得する、という意味。
以下のmanを参照。

man 3 printf

The flag characters

- The converted value is to be left adjusted on the field boundary. (The default is right jus‐
tification.) Except for n conversions, the converted value is padded on the right with
blanks, rather than on the left with blanks or zeros. A - overrides a 0 if both are given.


The precision
An optional precision, in the form of a period ('.') followed by an optional decimal digit string.
Instead of a decimal digit string one may write "*" or "*m$" (for some decimal integer m) to specify
that the precision is given in the next argument, or in the m-th argument, respectively, which must
be of type int. If the precision is given as just '.', the precision is taken to be zero. A nega‐
tive precision is taken as if the precision were omitted. This gives the minimum number of digits
to appear for d, i, o, u, x, and X conversions, the number of digits to appear after the radix char‐
acter for a, A, e, E, f, and F conversions, the maximum number of significant digits for g and G
conversions, or the maximum number of characters to be printed from a string for s and S conver‐
sions.


また、上記は以下と同じ結果。

$ sed -e "s/^\(.....\).*/\1/" file 
abced
abc
abced
abce
abced
abced
$ 

間違えやすいが(私だけかもしれないが)、これは、5文字より少ない場合は。sedで置換されずに、そのまま出力される。
よって、3文字などの場合は、patternにマッチせずにそのまま出力されている。

正規表現については、以下に詳しい説明があった。
Regular Expressions - sed, a stream editor