Naxels
Naxels

Reputation: 1745

dos / unix programming commands with | beginners question

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!

Upvotes: 0

Views: 297

Answers (4)

user414379
user414379

Reputation: 1

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

Upvotes: 0

Andre Holzner
Andre Holzner

Reputation: 18675

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

Upvotes: 1

aNish
aNish

Reputation: 1077

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"

Upvotes: 0

S.Lott
S.Lott

Reputation: 391852

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?

Upvotes: 0

Related Questions