0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

標準出力からの文字列を置換、変換して表示する(tr、sed)

Last updated at Posted at 2025-06-22

(自身の備忘録用です)

標準出力で文字列置換を行い表示する方法をいくつかメモ

置換したい文字数が同じ場合:tr

tr '置換したい文字列' '置換後の文字列' で可能

以下はCSV形式の出力を例にしたもの(可読性のため行数をつけてます)

$ echo "c0","c1","c2" | tr ',' '\n' | nl
     1	c0
     2	c1
     3	c2

以下は任意の文字列を例にしたもの(可読性のため行数をつけてます)

$ echo aaabbbccc | tr 'bbb' '\n' | nl -ba
     1	aaa
     2	
     3	
     4	ccc
※空行をわかりやすくするためnlコマンドにオプションを付与
 -ba(全ての行に対して行番号を付ける)

aaaとcccの2行のみ出力されて欲しかったが想定と違う結果に。
マニュアルを見ると、置換したい文字列と置換後の文字列は同じ文字数の想定で使われる模様。
そのため置換したい文字列の方が長い場合は、溢れた文字数分、置換後の文字列で指定した最後の文字で変換されてしまう。
この場合改行文字のみ指定しているのでbbb1つずつ全て改行になってしまう。

任意の文字列を変換したい場合:sed

置換したい文字列と置換後の文字列の文字数が一致しない、任意の文字列で変換したい場合はsedが使える。

sed 's/[置換したい文字列]/[置換後の文字列]/' で可能

$ echo aaabbbccc | sed 's/bbb/\n/' | nl
     1	aaa
     2	ccc
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?