Skip to content

Instantly share code, notes, and snippets.

@opplatek
Last active November 23, 2022 22:54
Show Gist options
  • Save opplatek/dfd31c04d782e69f21872c3b23e4e81e to your computer and use it in GitHub Desktop.
Save opplatek/dfd31c04d782e69f21872c3b23e4e81e to your computer and use it in GitHub Desktop.
Replace multiple spaces (characters) using sed
#!/bin/bash
#
# Replace one or more spaces (characters) with sed
# Important: there are two spaces before the * character
# Note: If you don't quote $text, echo will strip multiple spaces to just one
#
text="hello world"
echo "$text" | sed 's/ */X/g'
#helloXworld
text="hello world"
echo "$text" | sed 's/ */X/g'
#helloXworld
# I often use it with uniq -c which would create a similar output
text=" 2 a\n1 c\n3 b"
echo -e "$text" | sed 's/ */\t/g' | sed 's/^\t//g' | sort -k1n
#1 c
#2 a
#3 b
# Alternative is to use (Note: only one space here)
sed 's/ +//g'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment