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
To remove only the trailing newlines at the end of a file or string:
sed -i -e :a -e '/^\n*$/{$d;N;ba' -e '}' file.txt
-i
For a string (not a file):
echo -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:
str="hello " str="${str%$'\n'*}" echo "$str"
%
$'\n'*
awk
To remove only the trailing newlines in a file:
awk 'NR>1 && /^$/ {prev=$0; next} {print prev; prev=$0} END {if (prev != "") print prev}' file.txt > temp && mv temp file.txt
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