In Bash, you can strip the last consecutive newlines from a string or file using sed or parameter expansion. Here are a few ways:
sed (for files or strings)To remove only the trailing newlines at the end of a file or string:
bashsed -i -e :a -e '/^\n*$/{$d;N;ba' -e '}' file.txt
-i: Edit the file in-place.For a string (not a file):
bashecho -e "hello\n\n\n" | sed -e :a -e '/^\n*$/{$d;N;ba' -e '}'
If you have a string in a variable and want to remove only the trailing newlines:
bashstr="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.awk (for files)To remove only the trailing newlines in a file:
bashawk 'NR>1 && /^$/ {prev=$0; next} {print prev; prev=$0} END {if (prev != "") print prev}' file.txt > temp && mv temp file.txt
Vibe can make mistakes. Check answers. Learn more