views:

62

answers:

4

Hi,

I'm trying to do the following:

  1. get the last line of a file: tail -n 1 test.csv

  2. if this last line is END then continue(point 3), else quit

  3. get the amount of lines in the file: wc -l test.csv

  4. put these lines in a new file without the last line: head -n (length -1) test.csv > testdone.csv

(or if it's possible delete ONLY this line from the file)

Can someone please give me a full script on how to do this?

Thank you super much, been searching / trying for hours now!

A: 

Get the last line of a file: tail -n 1 test.csv. That works. What's your question?

if this last line is END then continue(point 3), else quit

That makes no sense since "last line of the file" is the last line. The END. There no more lines.

Get the amount of lines in the file: wc -l test.csv. That works. What's your question?

put these lines in a new file without the last line: head -n (length -1) test.csv > testdone.csv.

"These Lines" is vague, but the code shown looks great. What's your question?

S.Lott
the question is, can you give me the full script?
Paintrick
What "full script"? You have the three steps. You put them in one file. What more do you need? Please **update** the question to say specifically what you want that you don't have.
S.Lott
A: 

Try something like this.

#! /usr/bin/env sh

FILENAME="input.csv"
OUT="output.csv"

echo "Last line:"`tail -n 1 $FILENAME`
linecount=`wc -l $FILENAME|cut -d " " -f 1`
echo "No of lines:$linecount"
linecount=`expr $linecount - 1`
head -n $linecount $FILENAME > $OUT
echo "Copied to $OUT"
aNish
note the backticks around used in several places here. The backtick expressions are replaced by the shell by the output of the commands in backticks.
Andre Holzner
thanks, i seem to only not get the linecount part to work,when i test it in the commandline, the -f seems to be 3,but i still get no result
Paintrick
ok..Instead, you could use linecount=`wc -l < $FILENAME` instead of linecount=`wc -l $FILENAME|cut -d " " -f 1`as Andre Holzner has done below.
aNish
+1  A: 

on unix/linux try (in a script file):

#!/usr/bin/env bash
# 1
lastline=`tail -n 1 test.csv`

# 2
if [ "$lastline" == "END" ]; then
  exit
fi

# 3  (actually not needed)
num_lines=`wc -l < test.csv`

# 4 copy all except last line
sed \$d < test.csv > testdone.csv
Andre Holzner
thanks! that did it!filename=XXG.csvlastline=`tail -n 1 "$filename"`# if the last line is ENDif [ "$lastline" == "END" ]; then # copy all except last line sed \$d < "$filename" > po.csvfi
Paintrick
A: 

Which is the size of input file?

If it is not too large (less then 5 megabytes), then AWK can help you:

awk '{a[++i]=$0} END{if(a[i]~/^END$/){delete a[i];for(i in a){print a[i] >> "done-"FILENAME}}}' test.csv