Surender Raja
Surender Raja

Reputation: 3609

How to find min String from a delimited string in linux?

I have a delimited string stored in a variable.

date_str = 2017-04-03,2017-04-04,2017-04-05

How do I take the min value out of this delimited string using linux

Expected output is --> 2017-04-03

Could some one help me to do that?

Upvotes: 0

Views: 82

Answers (5)

signjing
signjing

Reputation: 98

Use this command: echo "date_str = 2017-04-03,2017-04-04,2017-04-05" | grep -Po "[0-9][^,]+" | sort -n | head -n 1

result is: 2017-04-03

Upvotes: 1

Olli K
Olli K

Reputation: 1760

Here's a solution that converts the strings to seconds from epoch, sorts them, grabs the first one and converts it back to a string:

date_str="2017-04-03,2017-04-04,2017-04-05"
while IFS=, read -r -a arr || [[ -n $arr ]]; do
    for str in ${arr[*]}; do
        echo $(date -d "$str" +%s)
    done
done <<<"$date_str" |
sort -n |
head -n 1 |
{ read -r earliest; date -d @"${earliest}" +%F ; }

Upvotes: 0

James Brown
James Brown

Reputation: 37424

Using awk:

$ awk -v d=$date_str '     # set variable to awk var d
BEGIN {
    n=split(d,a,",")       # split to a on ,
    for(i=1;i<=n;i++)      # iterate thru a
        if(m==""||a[i]<m)  # compare to current min m
            m=a[i]      
    print m                # after everything print min m
}'
2017-04-03

Regarding comments:

$ echo $date_str | awk -v RS=, 'NR==1||$0<m{m=$0}END{print m}'
2017-04-03

Upvotes: 1

Alex
Alex

Reputation: 1295

If you need sorting by date

#!/bin/sh

STR='2017-04-03,2017-04-04,2017-04-05,2017-02-23,2017-04-25,2017-03-12,2016-08-25';

TS_ARR=();
IFS=',' read -r -a dates <<< $STR
for next_date in ${dates[@]}; do
  date_ts=`date --date="${next_date}" +%s`
  TS_ARR+=($date_ts)
done
IFS=$'\n' SORT_TS=($(sort <<< "${TS_ARR[*]}"))
echo "sorted: `date -d @${SORT_TS[0]} +%Y-%m-%d`"

Should show you sorted: 2016-08-25

Upvotes: 0

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

Short gawk approach:

awk -v d=$date_str 'BEGIN{split(d,a,","); asort(a); print a[1]}'

The output:

2017-04-03

split(d,a,",") - splits "date" string into pieces separated by ,

asort(a) - sorts an array values

a[1] - represents the first item of sorted array

Upvotes: 3

Related Questions