user2328149
user2328149

Reputation: 737

How to get first and last element from a csv column

I have a csv file with the following format:

Time, Field1, Field2,
1000, 1,      2,
1001, 3,      4,
1002, 5,      6,

I want to get the first and last element from the time column and store them in variables in my bash script.

So, based in this example I need:

$start=1000
$end=1002

How can I do this?

Upvotes: 2

Views: 6551

Answers (4)

fumiyas
fumiyas

Reputation: 367

You can use sed -n 's/,.*//;2p;$p' file.csv to extract the first and last fields from the first column. From its output, you can separate each of them and read it into a variable like so:

{ 
    read start
    read end
} < <(sed -n 's/,.*//;2p;$p' file.csv)

The first read reads the first line into the variable $start, while the second read reads the second line of the output into the variable $end.

Upvotes: 0

You have a lot of alternatives. Here are some of them:

Using head, tail and cut

$start=$(head -n2 file.csv | tail -n1 | cut -d',' -f1)
$end=$(tail -n1 file.csv | cut -d',' -f1)

Using awk

$start=$(awk -F',' 'NR==2{print $1}' file.csv)
$end=$(awk -F',' 'END{print $1}' file.csv)

One-Liner using awk (thanks to this answer)

read start finish <<< $(awk -F',' 'NR==2{print $1}END{print $1}' file.csv)

Another One-Liner using awk

read -d'\n' start finish < <(awk -F',' 'NR==2{print $1}END{print $1}' file.csv)

Upvotes: 6

pic0
pic0

Reputation: 491

Also, try this:

start_end(){
 start=$(cat csv.file | head -n +2 | tail -n 1 | awk -F ',' '{print $1}')
 end=$(cat csv.file | tail -n 1 | awk -F ',' '{print $1}')
}

Upvotes: 1

anubhava
anubhava

Reputation: 786091

You can use a while loop like this:

while IFS=',' read -r c _; do
   ((end=c))
   ((start==0 && c>0)) && start=$c
done < file.csv

Check variables:

declare -p start end
declare -- start="1000"
declare -- end="1002"

Upvotes: 1

Related Questions