user6348718
user6348718

Reputation: 1395

Extract the value of nth column in the last line

I have a .csv file with the following data:

Name,Age,Gender
x,10,F
y,20,M
z,30,F
.
.
.

The no.of lines in the file always changes when I run something. How can I extract the Age for Name in the last line of the file. So far, I tried this:

  #!/bin/sh
  #extracting the headings and the last line values from the data.csv 
  file
  (head -1 data.csv && tail -1 data.csv) > dummy.txt 
  #this part doesn't work
  (sed -n "Name" data.csv && sed -n "Age" data.csv)>>dummy.txt

The above code errors out this:

sed: -e expression #1, char 13: unterminated `s' command*

Upvotes: 2

Views: 1097

Answers (2)

Jakub Jun
Jakub Jun

Reputation: 21

`tail -1 file | cut -d, -f2`
  • tail -1 gets the last line,
  • cut -d specifies the delimeter,
  • -f2 specifies the field

Upvotes: 1

Cyrus
Cyrus

Reputation: 88583

With awk:

awk -F "," 'END{print $2}' file

With GNU sed:

sed -rn '$s/.*,(.*),.*/\1/p' file

Output:

30

Upvotes: 2

Related Questions