In Bash how to strip last consecutive newlines?
Jul 5, 3:59pm

In Bash, you can strip the last consecutive newlines from a string or file using sed or parameter expansion. Here are a few ways:


1. Using sed (for files or strings)

To remove only the trailing newlines at the end of a file or string:

bash
sed -i -e :a -e '/^\n*$/{$d;N;ba' -e '}' file.txt
  • -i: Edit the file in-place.
  • The command removes only the trailing newlines at the end of the file.

For a string (not a file):

bash
echo -e "hello\n\n\n" | sed -e :a -e '/^\n*$/{$d;N;ba' -e '}'

2. Using Bash Parameter Expansion (for strings)

If you have a string in a variable and want to remove only the trailing newlines:

bash
str="hello

"
str="${str%$'\n'*}"
echo "$str"
  • % removes the shortest match of the pattern from the end.
  • $'\n'* matches one or more newlines at the end.

3. Using awk (for files)

To remove only the trailing newlines in a file:

bash
awk 'NR>1 && /^$/ {prev=$0; next} {print prev; prev=$0} END {if (prev != "") print prev}' file.txt > temp && mv temp file.txt

Jul 5, 3:59pm

This is a shared conversation and may include unverified content that doesn't reflect Mistral AI's views. Login to resume chatting.

Vibe can make mistakes. Check answers. Learn more