Tom's Guide | Tom's Hardware | Tom's Games
![]() |
![]() |
![]() |
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?

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|tacIn 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.txtHope this could help.
Xavier

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

![]() |
![]() |
![]() |

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