Computing.Net > Forums > Unix > how to delete last 3 lines of files

Computer Problems? Computing.Net has over 1,000,000 posts about all things technology related! Over 90% answered within 24 hours! Click here to start participating now! Also, be sure to check out the New User Guide.

how to delete last 3 lines of files

Reply to Message Icon

Name: heymulls
Date: September 7, 2004 at 02:29:09 Pacific
OS: unix
CPU/Ram: Ultra Sparc ,16 GB RAM
Comment:

I want to delete the last 3 lines in a set of files and then replace then with 3 different lines. The files are of different sizes.How do I do it?



Sponsored Link
Ads by Google

Response Number 1
Name: Xavier HECQUET
Date: September 7, 2004 at 07:05:34 Pacific
Reply:

Hello,

First of all, let me deal with the first part, that is to say removing the 3 trailing lines of your file. It strongly depends on your OS. Thus:

- On TRU64/AIX/Solaris:
You can use this:
tail -r MyFile.txt|tail +4|tail -r

- On Linux
tac MyFile.txt|tail +4|tac

In fact, the purpose is to reverse the file, then to get all lines except the 3 first ones (beginning then to the 4th), and to reverse the stream once again. All you have to do then is to redirect the stream to a file "... > MyNewFile.txt"

But of course I suppose you're on HPUX... ;-)
ok, it's a bit harder. Here, I can purpose you the following:
l1=`wc -l MyFile.txt|cut -f1 -d' '`;l2=`expr $l1 - 3`;head -$l2 MyFile.txt
which you can also redirect to a new file.

Then, you have to put your 3 last lines. If these lines are in a text file:
cat MyNewFile.txt TheLines.txt > MyLastNewFile.txt
If this is in a script:
echo $Line1 >> MyNewFile.txt
echo $Line2 >> MyNewFile.txt
echo $Line3 >> MyNewFile.txt

Hope this could help.

Xavier


0

Response Number 2
Name: Jim Boothe
Date: September 7, 2004 at 07:46:07 Pacific
Reply:

And here is a sed solution ...

for filename in file1 file2 file3
do
sed -e '
1N
$!N
$!P
$!D
$a\
newline 1\
newline 2\
newline 3
$d
' $filename > ${filename}new
done


0

Response Number 3
Name: heymulls
Date: September 7, 2004 at 08:14:01 Pacific
Reply:

Thanks for the response!!
Was of great help.


0

Sponsored Link
Ads by Google
Reply to Message Icon

Related Posts

See More







Post Locked

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.


Go to Unix Forum Home


Sponsored links

Ads by Google


Results for: how to delete last 3 lines of files

Delete last character in a file www.computing.net/answers/unix/delete-last-character-in-a-file/5310.html

How to delete duplicate lines ?? www.computing.net/answers/unix/how-to-delete-duplicate-lines-/8277.html

How to delete a file named -x www.computing.net/answers/unix/how-to-delete-a-file-named-x/3350.html