LoginSignup
5
6

More than 5 years have passed since last update.

改行コードの変更

Last updated at Posted at 2018-07-05

はじめに

ダウンロードしてきたshellスクリプトが動かない、などで改行コードを変えたい時があります。

改行コード
mac : \r
unix : \n
dos : \r\n

mac は ウィキペディアに、バージョンに関連しての違いについて説明がありました。

ウィキペディア
コモドールによるシステム、Apple IIファミリ、Mac OS(バージョン9まで)、OS-9。

発生するエラー

shell scriptを実行しようとすると次のようなエラーがでます。

error
$ ./test.sh.sh
bash: ./test.sh.sh: /bin/sh^M: bad interpreter: No such file or directory

vimで改行コード変更

:set fileformat の略で :se ff が使えます。

vi
変更
:se ff=dos
:se ff=unix
:se ff=mac

現在の改行コード確認
:se ff

tr コマンドで変更

\r\n を \n にしたいことが多いので、そのやり方です。

tr
$ tr -d "\r" < test.sh.sh > test.sh
$ chmod 755 test.sh
$ ls -al test.sh*
-rwxr-xr-x.  1 test    test      22 Jul  5 23:57 test.sh
-rwxr-xr-x.  1 test    test      24 Jul  5 23:44 test.sh.sh

sed で変更

sed で置換するやり方です。

sed
unix > windows
$ sed -e 's/$/\r/g' test.sh > test.sh.sh

windows > unix
$ sed -e 's/\r//g' test.sh.sh > test.sh

Windowsで変更

Windowsではよく使うエディタで変更するのがいいですね。notepad もそのうち対応することが発表されてました。
Introducing extended line endings support in Notepad – Windows Command Line Tools For Developers

参考

Man page of TR
Man page of SED

5
6
2

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
5
6