| この記事の要点 |
|---|
|
改行コードの種類
| OS | 改行コード | 表記 |
|---|---|---|
| Windows | CR + LF | \\r\\n (0x0D 0x0A) |
| Unix / Linux / macOS (現代) | LF | \\n (0x0A) |
| macOS (9 以前) | CR | \\r (0x0D) |
Java
String text = "line1\nline2\r\nline3\rline4";
// 全種類の改行を削除
String result = text.replaceAll("\\r?\\n|\\r", "");
// → "line1line2line3line4"
// 改行を半角スペースに置換
String result = text.replaceAll("\\r?\\n", " ");
// 末尾の改行のみ削除 (trim)
String result = text.replaceAll("\\s+$", "");
// 連続改行を 1 つに正規化
String result = text.replaceAll("(\\r?\\n)+", "\n");
// 行ごとに処理 → 結合
String result = String.join("", text.split("\\r?\\n"));
// Java 11+ String.lines() を使う
String result = text.lines().collect(Collectors.joining());
PHP
<?php
$text = "line1\nline2\r\nline3\rline4";
// 全種類の改行を削除
$result = str_replace(["\r\n", "\r", "\n"], "", $text);
// または preg_replace
$result = preg_replace("/\\r?\\n|\\r/", "", $text);
// 改行をスペースに
$result = str_replace(["\r\n", "\r", "\n"], " ", $text);
// 末尾の改行のみ削除
$result = rtrim($text);
$result = rtrim($text, "\r\n"); // 改行のみ指定
// 各種 trim
$result = trim($text); // 前後の空白・改行を全削除
$result = ltrim($text); // 前のみ
$result = rtrim($text); // 後のみ
// 連続改行の正規化
$result = preg_replace("/(\\r?\\n){2,}/", "\n", $text);
// PHP_EOL 定数(OS 別の改行)
$result = str_replace(PHP_EOL, "", $text);
Python
text = "line1\nline2\r\nline3\rline4"
# 全種類の改行を削除
result = text.replace("\r\n", "").replace("\n", "").replace("\r", "")
# 正規表現で一括
import re
result = re.sub(r"\r?\n|\r", "", text)
# 行に分割 → 結合
result = "".join(text.splitlines())
# 改行をスペースに
result = re.sub(r"\r?\n", " ", text)
# 末尾の改行のみ削除
result = text.rstrip()
result = text.rstrip("\r\n")
# 前後の空白・改行を全削除
result = text.strip()
# 連続改行の正規化
result = re.sub(r"(\r?\n)+", "\n", text)
# ファイル読み込み時の改行除去
with open("file.txt") as f:
lines = [line.rstrip() for line in f]
JavaScript
const text = "line1\nline2\r\nline3\rline4";
// 全種類の改行を削除
const result = text.replace(/\r?\n|\r/g, "");
// 改行をスペースに
const result = text.replace(/\r?\n/g, " ");
// 末尾の改行のみ削除
const result = text.replace(/\s+$/, "");
const result = text.trimEnd(); // ES2019
// 前後の空白・改行を全削除
const result = text.trim();
// 連続改行の正規化
const result = text.replace(/(\r?\n)+/g, "\n");
// 行ごとに処理
const lines = text.split(/\r?\n/);
const result = lines.join("");
シェル / コマンドライン
sed
# 全改行削除(tr が確実)
$ echo -e "line1\nline2" | tr -d "\n"
line1line2
# CR (\r) のみ削除 (CRLF → LF 変換)
$ sed -i "s/\r//g" file.txt
# Windows 改行 → Unix 改行
$ dos2unix file.txt
# 逆
$ unix2dos file.txt
# 連続改行を 1 つに
$ sed -i "/^$/d" file.txt # 空行削除
$ awk "NF" file.txt # 同上
awk
# 各行末の \r を削除
$ awk "{sub(/\r$/, \"\")} 1" file.txt
# 全改行を削除(1 行に結合)
$ awk "{printf \"%s\", \$0}" file.txt
SQL での改行削除
MySQL
-- 改行をスペースに置換
UPDATE users
SET description = REPLACE(REPLACE(description, CHAR(13), ' '), CHAR(10), ' ')
WHERE id = 1;
-- 改行を削除
UPDATE users
SET description = REPLACE(REPLACE(description, CHAR(13), ''), CHAR(10), '');
-- 検索(改行を含むレコード)
SELECT * FROM users WHERE description LIKE CONCAT('%', CHAR(10), '%');
PostgreSQL
-- 改行削除
UPDATE users
SET description = REPLACE(REPLACE(description, E'\n', ''), E'\r', '');
-- 正規表現
UPDATE users
SET description = REGEXP_REPLACE(description, E'\r?\n|\r', '', 'g');
Oracle
-- 改行削除
UPDATE users
SET description = REPLACE(REPLACE(description, CHR(13), ''), CHR(10), '');
用途別の使い分け
| 用途 | 手法 |
|---|---|
| CSV エクスポートで改行を半角空白に | 正規表現で \\r?\\n → スペース |
| ファイル末尾の改行のみ削除 | rstrip() / trimEnd() |
| 連続改行を 1 つに正規化 | 正規表現 (\\r?\\n)+ |
| Windows ⇄ Unix 変換 | dos2unix / unix2dos |
| HTML 表示用 | nl2br()(PHP)等で <br> に |
注意点
- OS による違い: ファイル受け渡し時は Windows / Mac / Unix の改行を全部考慮
- UTF-8 BOM: ファイル先頭の
\\xEF\\xBB\\xBFも別途削除が必要なことがある - 正規表現の挙動: 各言語で
\\r/\\nの扱いが微妙に違う - パフォーマンス: 大量データなら正規表現より
str_replace系の方が速い
関連記事
子ページ
子ページはありません
人気ページ
- 1 Eclipseで「サーバーに追加または除去できるリソースがありません。」の原因と対処法
- 2 tomcat の起動 / 停止ログと catalina.log・catalina.out の違い
- 3 JavaScript で base URL を取得する方法|window.location.origin
- 4 YouTube Data API v3 エラー一覧|403・400・404 の原因と対処
- 5 Laravel エラー一覧|500/Blade/DB 接続/ルーティングの代表エラー
- 6 3Dグラフィックスとは|モデリング/レンダリング/主要ソフトウェア (Blender / Maya)
- 7 Spring Frameworkのアノテーション一覧
- 8 【Spring】@Valueアノテーションとは
- 9 CATALINA_HOME の確認方法 (Linux / Mac)
- 10 【Spring】@Autowiredアノテーションとは
最近更新/作成されたページ
- プロジェクトをTomcatプロジェクトとして認識させる方法 2026-10-07 22:32:50
- MySQLの1366 Incorrect string value|Laravelの文字コード・絵文字エラー 2026-10-07 21:54:03
- curlの証明書ホスト名不一致|旧エラー51・現行60の確認と対処 2026-10-07 21:54:03
- LaravelのMassAssignmentException|fillableの原因と安全な対処 2026-10-07 21:54:03
- Eclipse で Tomcat の起動ログがコンソールに出ない時の確認手順 2026-10-07 21:54:02
- MySQLにおける中央値(Median)の導き方(バージョン8未満) 2026-10-07 13:49:45
- getInputForward 2026-10-07 13:41:15
- JSONから配列に変換 2026-10-07 13:41:15
- ビューから値をモデルに格納しコントローラーで受け取る方法 2026-10-07 13:23:41
- Laravelのテーブル作成と定義変更|マイグレーション・up/down・注意点 2026-10-07 13:23:41
- NumPy 配列に要素を追加する方法 (append / concatenate) 2026-10-07 13:23:41
- MariaDB・MySQLで現在日時を取得する方法|NOW・タイムゾーン・保存型 2026-10-07 13:13:36
- 【django】テンプレートで定数を使用する方法 2026-10-07 13:10:15
- Spring BootにおけるApplication.propertiesの環境依存設定の分割方法 2026-10-07 12:09:35
- Not supported for DML operations【Springエラー】 2026-10-07 11:09:38