LoginSignup
3
3

More than 3 years have passed since last update.

BashでファイルにCRLFが含まれているかを判断してLFに置換する

Last updated at Posted at 2019-06-17

Bashで、テキストファイルの行末コードがCRLFになっているかを、なるべく短くてビルトインのコマンドで判断する・置換するコードです。

ファイルにCRLFが含まれているかを判断する

grep -U $'\r' winfile.txt

if文で処理を分ける場合

if grep -q -U $'\r' winfile.txt; then
  # CRLFである場合の処理
else
  # そうでない場合の処理
fi

行末のCRLFをLFに統一する

sed 's/'$'\r''$//' winfile.txt

置換した結果を別ファイルに吐き出す場合

sed 's/'$'\r''$//' winfile.txt > out.txt

直接ファイルを上書きする場合

sed -i 's/'$'\r''$//' winfile.txt

macOSなどBSD系だと、バックアップ拡張子が必要。

sed -i.bak -e 's/'$'\r''$//' winfile.txt
3
3
1

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
3