Skip to content

Instantly share code, notes, and snippets.

@Ezka77
Created January 11, 2019 09:02
Show Gist options
  • Save Ezka77/734fc619521940f6bb026ee053d53995 to your computer and use it in GitHub Desktop.
Save Ezka77/734fc619521940f6bb026ee053d53995 to your computer and use it in GitHub Desktop.
Remove text file newlines with sed
#!/usr/bin/env sh
# How to remove all newlines (\n) from a text file by using sed ? (from stackoverflow)
replace=${1}
file=${2}
sed ':a;N;$!ba;s/\n/${replace}/g' ${file}
# This will read the whole file in a loop, then replaces the newline(s) with a space.
# Explanation:
# Create a label via :a.
# Append the current and next line to the pattern space via N.
# If we are before the last line, branch to the created label $!ba ($! means not to do it on the last line as there should be one final newline).
# Finally the substitution replaces every newline with a space on the pattern space (which is the whole file)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment