3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

シェル — BSD版のsedでテキストを改行「に」置換をする方法

Last updated at Posted at 2018-08-23

過去にも何度かハマったが、その頃はBSDやGNUの違いがあるということも知らず、なんとなくの理解で終わってた案件。

結論

使えるならGNU版を使おう。

GNUの例

echo 'A:B:C' | sed 's/:/\n/g'
A
B
C

何の不思議もなく直感的に使える。


  • sed (GNU sed) 4.4
  • docker run --interactive --tty ubuntu /bin/bash

BSD版

こんな風に書かないといけないっぽい。

echo 'A:B:C' | sed 's/:/\
/g'

A
B
C

または

echo 'A:B:C' | sed -e 's/:/\'$'\n/g'
A
B
C

嘘だろ。

'$' の記号の意味も知らないし、調べたいとも思わないぐらい。


  • Mac OS X High Sierra
  • GNU bash, version 4.4.0(1)-release (x86_64-apple-darwin15.6.0)

BSDの他のコマンド例

以下の書き方はどれも期待しない結果。

echo 'A:B:C' | sed -e 's/:/\n/g'
AnBnC
echo 'A:B:C' | sed 's/:/\n/g'
AnBnC
echo 'A:B:C' | sed 's/:/\\n/g'
A\nB\nC
echo 'A:B:C' | sed 's/:/\r/g'
ArBrC
echo 'A:B:C' | sed 's/:/\\r/g'
A\rB\rC
echo 'A:B:C' | sed "s/:/\n/g"
AnBnC
echo 'A:B:C' | sed "s/:/\\n/g"
AnBnC
echo 'A:B:C' | sed "s/:/\\r/g"
ArBrC
echo 'A:B:C' | sed "s/:/\r/g"
ArBrC
echo 'A:B:C' | sed "s/:/\r\n/g"
ArnBrnC
echo 'A:B:C' | sed "s/:/\\r\\n/g"
ArnBrnC
echo 'A:B:C' | sed "s/:/\\\r\\\n/g"
A\r\nB\r\nC

あわせて読みたい?

Ref

Links

チャットメンバー募集

何か質問、悩み事、相談などあればLINEオープンチャットもご利用ください。

Twitter

3
2
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
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?