0

I am trying to sort files in a directory, depending on the 'date string' attached in the file name, for example files looks as below SSA_F12_05122013.request.done SSA_F13_12142012.request.done SSA_F14_01062013.request.done Where 05122013,12142012 and 01062013 represents the dates in format. Please help me in providing a unix shell script to sort these files on the date string present in their file name(in descending and ascending order).

Thanks in advance.

4

4 回答 4

3

Hmmm... why call on heavyweights like awk and Perl when sort itself has the capability to define what exactly to sort by?

ls SSA_F*.request.done | sort -k 1.13,1.16 -k 1.9,1.10 -k 1.11,1.12 

Each -k option defines a "sort key":

-k 1.13,1.16

This defines a sort key ranging from field 1, column 13 to field 1, column 16. (A field is by default delimited by whitespace, which your filenames don't have.)

If your filenames are varying in length, defining the underscore as field separator (using the -t option) and then addressing columns in the third field would be the way to go.

Refer to man sort for details. Use the -r option to sort in descending order.

于 2013-04-17T12:27:58.980 回答
0
ls -lrt *.done | perl -lane '@a=split /_|\./,$F[scalar(@F)-1];$a[2]=~s/(..)(..)(....)/$3$2$1/g;print $a[2]." ".$_' | sort -rn | awk '{$1=""}1'
于 2013-04-17T11:04:08.690 回答
0

one way with awk and sort:

ls -1|awk -F'[_.]' '{s=gensub(/^([0-9]{4})(.*)/,"\\2\\1","g",$3);print s,$0}'|sort|awk '$0=$NF'

if we break it down:

ls -1|
awk -F'[_.]' '{s=gensub(/^([0-9]{4})(.*)/,"\\2\\1","g",$3);print s,$0}'|
sort|
awk '$0=$NF'

the ls -1 just example. I think you have your way to get the file list, one per line.

test a little bit:

kent$  echo "SSA_F13_12142012.request.done
SSA_F12_05122013.request.done
SSA_F14_01062013.request.done"|awk -F'[_.]' '{s=gensub(/^([0-9]{4})(.*)/,"\\2\\1","g",$3);print s,$0}'|
sort|
awk '$0=$NF'
SSA_F13_12142012.request.done
SSA_F14_01062013.request.done
SSA_F12_05122013.request.done
于 2013-04-17T12:07:19.737 回答
0
ls *.done | perl -pe 's/^.*_(..)(..)(....)/$3$2$1$&/' | sort -rn | cut -b9-

this would do +

于 2013-04-17T12:24:35.907 回答