On Linux how to remove last new line character, even if the last line is not empty?
2/2
Jun 3, 2:19pm

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:


1. Using sed

bash
sed -i -e '${/^$/d;}' -e ':a;/^\n*$/{$d;N;ba;}' file.txt
  • This removes the last newline, even if the last line is not empty.

2. Using tr (for a single trailing newline)

bash
tr -d '\n' < file.txt > temp && mv temp file.txt
  • This removes all newlines, so it's only suitable if you want to remove the last one and the file has no other newlines.

3. Using awk

bash
awk 'NR>1{printf "%s", prev} {prev=$0} END{printf "%s", prev}' file.txt > temp && mv temp file.txt
  • This prints all lines without adding a newline at the end.

4. Using head (if the file has at least one line)

bash
head -c -1 file.txt > temp && mv temp file.txt
  • This removes the last character (which is a newline if the file ends with one).

5. Using perl

bash
perl -pi -e 'chomp if eof' file.txt
  • This removes the last newline if it exists.

Which one should you use?

  • For most cases, sed or perl are the most reliable.
  • If you want to remove only the last newline and keep the rest of the file intact, use sed or perl.
2/2
Jun 3, 2:20pm

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