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

how to delete last 3 lines of files

Reply to Message Icon

Original Message
Name: heymulls
Date: September 7, 2004 at 02:29:09 Pacific
Subject: how to delete last 3 lines of files
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?


Report Offensive Message For Removal


Response Number 1
Name: Xavier HECQUET
Date: September 7, 2004 at 07:05:34 Pacific
Subject: how to delete last 3 lines of files
Reply: (edit)

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


Report Offensive Follow Up For Removal

Response Number 2
Name: Jim Boothe
Date: September 7, 2004 at 07:46:07 Pacific
Subject: how to delete last 3 lines of files
Reply: (edit)

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


Report Offensive Follow Up For Removal

Response Number 3
Name: heymulls
Date: September 7, 2004 at 08:14:01 Pacific
Subject: how to delete last 3 lines of files
Reply: (edit)

Thanks for the response!!
Was of great help.


Report Offensive Follow Up For Removal







Use following form to reply to current message:

   Name: From My Computing.Net Settings
 E-Mail: From My Computing.Net Settings

Subject: how to delete last 3 lines of files

Comments:

 


  Homepage URL (*): 
Homepage Title (*): 
         Image URL: 
 
Data Recovery Software