Skip to content
The Chat Archive
gpt-4.1-mini-2025-04-14· OpenAI LMArena Human Preference 140K

delete last 3 lines in file in bash ?

  1. User

    delete last 3 lines in file in bash ?

  2. 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 head

    head -n -3 filename > temp && mv temp filename
    
    • head -n -3 filename prints all but the last 3 lines.
    • Redirect output to a temporary file.
    • Replace the original file with the temp file.

    Method 2: Using sed

    sed -i '' -e :a -e '$d;N;2,3ba' -e 'P;D' filename
    

    This is a bit complex and may vary by sed version. A simpler portable way is:

    sed -i -e :a -e '$d;N;2,3ba' -e 'P;D' filename
    

    But this is tricky and not very readable.


    Method 3: Using head with wc (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!

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.