sed operates on lines, excluding the newline character, so it cannot directly remove newlines within a line using standard commands. The newline is stripped before processing and added back after. To remove or replace newlines, you need special techniques:
-
Replace all newlines with spaces:
sed -e ':a;N;$!ba;s/\n/ /g' fileThis reads the entire file into the pattern space and replaces all newlines with spaces.
-
Remove all newlines (flatten to one line):
sed -z 's/\n//g' fileThe
-zoption treats input as null-separated, allowingsedto process newlines as data. -
Remove only trailing newlines:
sed -z '$ s/\n$//' fileThis removes the final newline, useful when preserving the POSIX text file standard.
-
Remove newlines only between specific patterns (e.g., lines not ending with
"):sed '/"$/{:a;N;s/\n//;ta}' fileThis appends lines until a line ends with
"and removes newlines in between.
For simple cases, tr -d '\n' is often faster and more reliable than sed.