Home > database >  Extract hours from csv using bash-script
Extract hours from csv using bash-script

Time:11-10

I have csv file having below details, want to fetch the details based on time like if hour is in betwwen 10 and 18 it should print be as morning, and rest of lines print night.

time,id
2022-08-01T00:09:14 09:00,PKA990
2022-08-01T06:48:24 09:00,PKA990
2022-08-01T08:27:23 09:00,
2022-08-01T11:04:18 09:00,ABCD890
2022-08-01T11:23:22 09:00,ABCD890
2022-08-01T11:30:14 09:00,
2022-08-01T12:01:12 09:00,ABCD890
2022-08-01T15:11:59 09:00,JIKOPL8
2022-08-01T18:20:53 09:00,TUVNDGD

im expecting output be like

time,id,session
2022-08-01T00:09:14 09:00,PKA990,night
2022-08-01T06:48:24 09:00,PKA990,night
2022-08-01T08:27:23 09:00,LOADING,night
2022-08-01T11:04:18 09:00,ABCD890,morning
2022-08-01T11:23:22 09:00,ABCD890,morning
2022-08-01T11:30:14 09:00,LOADING,morning
2022-08-01T12:01:12 09:00,ABCD890,morning
2022-08-01T15:11:59 09:00,JIKOPL8,morning
2022-08-01T18:20:53 09:00,TUVNDGD,night

Please suggest.

Sorry i haved edited some rows .... when ever there is an blank it should fill with "LOADING"

apologize

CodePudding user response:

Here an awk solution:

#! /bin/bash

awk '
BEGIN {
    FS=OFS=","
}
NR == 1 {
    print $0, "session"
    next
}
$1 ~ /^[-0-9] T(10|11|12|13|14|15|16|17):/ {
    print $0, "morning"
    next
}
{
    print $0, "night"
}

' <"datetime.csv"

Output:

time,id,session
2022-08-01T00:09:14 09:00,PKA990,night
2022-08-01T06:48:24 09:00,PKA990,night
2022-08-01T08:27:23 09:00,<blank>,night
2022-08-01T11:04:18 09:00,ABCD890,morning
2022-08-01T11:23:22 09:00,ABCD890,morning
2022-08-01T11:30:14 09:00,<blank>,morning
2022-08-01T12:01:12 09:00,ABCD890,morning
2022-08-01T15:11:59 09:00,JIKOPL8,morning
2022-08-01T18:20:53 09:00,TUVNDGD,night

CodePudding user response:

A pure bash solution:

#! /bin/bash

INPUT_FILENAME="datetime.csv"
FLAG_FIRST=1
while read -r LINE; do
    if [[ ${FLAG_FIRST} -eq 1 ]]; then
        printf "%s,session\n" "${LINE}"
        FLAG_FIRST=0
        continue
    fi
    [[ -z "${LINE}" ]] && continue
    if [[ "${LINE}" =~ ^[-0-9] T(10|11|12|13|14|15|16|17): ]]; then
        printf "%s,morning\n" "${LINE}"
    else
        printf "%s,night\n" "${LINE}"
    fi
done < <(cat "${INPUT_FILENAME}"; echo)

Output:

time,id,session
2022-08-01T00:09:14 09:00,PKA990,night
2022-08-01T06:48:24 09:00,PKA990,night
2022-08-01T08:27:23 09:00,<blank>,night
2022-08-01T11:04:18 09:00,ABCD890,morning
2022-08-01T11:23:22 09:00,ABCD890,morning
2022-08-01T11:30:14 09:00,<blank>,morning
2022-08-01T12:01:12 09:00,ABCD890,morning
2022-08-01T15:11:59 09:00,JIKOPL8,morning
2022-08-01T18:20:53 09:00,TUVNDGD,night
  • Related