gpt-4.1-mini-2025-04-14· OpenAI LMArena Human Preference 140K
delete last 3 lines in file in bash ?
- User
delete last 3 lines in file in bash ?
- Assistant
To delete the last 3 lines of a file in Bash, you can use several methods. Here are some common approaches:
Method 1: Using
headhead -n -3 filename > temp && mv temp filenamehead -n -3 filenameprints all but the last 3 lines.- Redirect output to a temporary file.
- Replace the original file with the temp file.
Method 2: Using
sedsed -i '' -e :a -e '$d;N;2,3ba' -e 'P;D' filenameThis is a bit complex and may vary by
sedversion. A simpler portable way is:sed -i -e :a -e '$d;N;2,3ba' -e 'P;D' filenameBut this is tricky and not very readable.
Method 3: Using
headwithwc(more portable)lines=$(wc -l < filename) head -n $((lines - 3)) filename > temp && mv temp filename
Summary
The easiest and most common way is:
head -n -3 filename > temp && mv temp filename
If you want me to provide a script or handle edge cases (like files with fewer than 3 lines), just ask!
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.