To remove the last newline character from a file in Linux, even if the last line is not empty, you can use one of these methods:
sed
sed -i -e '${/^$/d;}' -e ':a;/^\n*$/{$d;N;ba;}' file.txt
tr
tr -d '\n' < file.txt > temp && mv temp file.txt
awk
awk 'NR>1{printf "%s", prev} {prev=$0} END{printf "%s", prev}' file.txt > temp && mv temp file.txt
head
head -c -1 file.txt > temp && mv temp file.txt
perl
perl -pi -e 'chomp if eof' file.txt
Which one should you use?
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