Best way to remove last line-feed in text file
(as echo -n will remove all trailing newline characters)
MacBook /, Mac OS X (10.6.3), / Windows xp (Boot Camp)
MacBook /, Mac OS X (10.6.3), / Windows xp (Boot Camp)
What is the best way to remove last line-feed in text file? (so that the last line of text is the last line, not a line-feed). The best I can come up with is: echo -n "$(cat file.txt)" > newfile.txt
(as echo -n will remove all trailing newline characters)
tr ' ' ' ' <file.txt >newfile.txt
perl -ne '
chomp;
print " " if $n++ != 0;
print;
' file.txt >newfile.txt
perl -ne '
chomp;
print " " if $n++ != 0;
print;
' file.txt >newfile.txt
sed '$d' < file1 > file2; mv file2 file1
Line 1
Last Line
Line 1
Line 1
Last Line
BobHarris wrote:
What is the best way to remove last line-feed in text file? (so that the last line of text is the last line, not a line-feed). The best I can come up with is: echo -n "$(cat file.txt)" > newfile.txt
(as echo -n will remove all trailing newline characters)
According to my experiments, you have removed all line terminators from the file, and replaced those between lines with a space.
awk 'NR > 1 { print h } { h = $0 } END { ORS = ""; print h }' inputfile
file='/path/to/file'
[[ "$(tail -c 1 "${file}" | tr -dc ' ' | wc -c)" -eq 1 ]] &&
printf "" | dd of="${file}" seek=$(($(stat -f "%z" "${file}") - 1)) bs=1 count=1
tail -c 10 "${file}"; echo
file='/path/to/file'
[[ "$(tail -c 1 "${file}" | tr -dc ' ' | wc -c)" -eq 1 ]] &&
printf "" | dd of="${file}" seek=$(($(stat -f "%z" "${file}") - 1)) bs=1 count=1
tail -c 10 "${file}"; echo
... If an initial portion of the output file is
seeked past (see the oseek operand), the output file is trun-
cated at that point.
Best way to remove last line-feed in text file