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.

Revisions

  1. kekneus373 created this gist Feb 10, 2026.
    30 changes: 30 additions & 0 deletions sed-remove-linebreaks.md
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,30 @@
    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**:
    ```bash
    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)**:
    ```bash
    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**:
    ```bash
    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 `"`):
    ```bash
    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`.