2

I have a csv file and need to fetch the last row nth column value.So i have two queries on the same which are

  1. how to do the same ?
  2. does it internally loops for all the records in the csv all the way
    down to the last row to fetch the data as in that case i think we will
    have some performance issues if its a large csv file.

Thanks

Sam
  • 728
  • 1
  • 9
  • 26
  • `tail` can get you the last row. `awk` could get a column. For example [Extract one column from CSV](http://stackoverflow.com/questions/19602181/bash-extract-one-column-of-a-csv-file) – OneCricketeer Oct 03 '16 at 09:33
  • `tail -1 file.csv | awk -F, '{print $5}'` to print 5th column of last row – anubhava Oct 03 '16 at 09:34
  • `awk -F, 'END{ print $N}' file.csv` , where `N` is any column number of last row as per requirement. @Inian deleting old comment as it's confusing. – P.... Oct 03 '16 at 09:44
  • Thanks a lot for the help ... tail -1 file.csv | awk -F, '{print $5}' => this prints the 5th column value.But in my case i need to store it in a variable and it should not print the value.Just wanted to know how can we do this.I have something like this now -> tail -1 $FILE | awk -F, '{print $4}' – Sam Oct 03 '16 at 10:05
  • So basically now i have this -> tail -1 $FILE | awk -F, '{print $4}' and i want to store the output without printing the same.So please suggest how can we do the same. – Sam Oct 03 '16 at 10:28

2 Answers2

0

Came to know that I was facing issues due to white spaces and other double quotes which were coming when i was fetching the value from csv file. Resolved the issue by a combination of trans and awk and truncate.

value=`tail -1 file.csv | awk -F',' '{print $5}' | tr -s ' ' '_' | tr -d '"'`
ech $value
Sam
  • 728
  • 1
  • 9
  • 26
0

You can also do something like this using cut command..

 >Wed Oct 05|01:47:01|gaurav@[STATION]:/root/ga/scripts/temp/tmp % cat c.csv |head -3
1,2,3,4,5,6,7,8
1,2,3,4,5,6,7,8
1,2,3,4,5,6,7,8
 >Wed Oct 05|01:47:04|gaurav@[STATION]:/root/ga/scripts/temp/tmp % cat c.csv |cut -f7 -d","|head -3
7
7
7
 >Wed Oct 05|01:47:06|gaurav@[STATION]:/root/ga/scripts/temp/tmp %
User9102d82
  • 1,172
  • 9
  • 19