Problem using head to remove last line of file

Étienne Bézout

I was recently looking for a way to remove the last line of a file foo.txt and came across the following solution

head -n -1 foo.txt temp.txt; mv temp.txt foo.txt

which works fine. However, I also tried simply

head -n -1 foo.txt > foo.txt

which to my surprise left foo.txt an empty text file, and I would like to know why.

I'm just getting started with unix, so it's possible my question is rather silly.

Sobrique

Because the redirect > happens before the rest of the command.

If you want to do an inplace edit, you'll need a suitably aware utility. e.g. perl or sed. (Or just do the mv like the original snippet suggested)

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

how to remove both first and last line of csv file using sed

spark how to remove last line in a csv file

Remove the last line from a file in Bash

Remove last line from file excerpt

Remove the last line from the text file (including empty lines) using batch

Remove LAST blank line from a text file containing paragraphs using notepad++

How to remove a comma 2nd to the last line of the file using SED?

Remove the last page of a pdf file using PDFtk?

remove last n characters of a file using batch

Skip last 5 line in a file using python

delete last line in text file using batch

Remove a last blank line

How can I remove text on the last line of a file?

AWK - remove all but last occurance of log file line based on time

Read and remove first (or last) line from txt file without copying

Remove the last empty line from each text file

How remove the last brak line from the txt file with JAVA?

How do I remove last line from text file in C

Remove last blank line from text file PYTHON

Getting head to display all but the last line of a file: command substitution and standard I/O redirection

All but the last part of a pipeline is ignored, using sed file | sed file | head file

remove line comment from file by using regex

Remove line from php file using sed

How to Remove last comma of each line on csv using linux

how to remove last comma from line in bash using "sed or awk"

head file with windows line endings

Export every line (excpet last line ) of a file to create a new file for each line using AWK

Deleting last line of a file

Append to last line of file