Using sed with variables (again!)

Hi,

I'm trying to use sed to delete the last three lines of a file. I currently have:

# get the amount of lines in the file
foldernum=`wc -l File_In.txt | cut -c1-8`
# remove the lines in the file
sed "${foldernum}-3,${foldernum}d" File_In.txt > File_Out.txt

I get the error - sed: unknown command

Is there a better way or have I simply got my syntax incorrect.

Cheers.

Another way:

awk -v var=`wc -l < File_In.txt` 'NR==var-2{exit}1' File_In.txt > File_Out.txt

Regards

I tried the code above but it didn't trim the last 3 lines of the file.

You need to do the arithmetic separately, sed doesn't know how to subtract. awk does know; do you get an error message or does it just not do what you want? Maybe you need mawk/nawk/gawk/XPG4 awk if your default awk is a really old "traditional" awk.

foldernum=`wc -l <File_In.txt`  # note use of redirection
limit=`expr $foldernum - 3`
sed -e "$limit",'$d' File_In.txt >File_Out.txt

For the awk command I didn't get an error message but it didn't do what I wanted.

However, I've played around with the code you provided and I got it to work accordingly.

Thanks.

It works fine for me, maybe you should use gawk, nawk or /usr/xpg4/bin/awk on Solaris as era mentioned.

Regards