Skip to content

Instantly share code, notes, and snippets.

@kekneus373
Created February 10, 2026 18:20
Show Gist options
  • Select an option

  • Save kekneus373/75a381456835f3cbb9284eb1b31cced3 to your computer and use it in GitHub Desktop.

Select an option

Save kekneus373/75a381456835f3cbb9284eb1b31cced3 to your computer and use it in GitHub Desktop.
Remove Line Breaks with Sed

Remove Line Breaks with Sed

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' file

    This 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' file

    The -z option treats input as null-separated, allowing sed to process newlines as data.

  • Remove only trailing newlines:

    sed -z '$ s/\n$//' file

    This 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}' file

    This 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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment