Select older file if multiple file exists with same name

Hi

I want to select older file if multiple files exist with same name.
eg:There are five files in UNIX folder

  1. Sample1_20091231
  2. Sample1_20100110
  3. Sample1_20100115
  4. Sample2_20100115
  5. Sample3_20100115

However in file list i.e FileName.DAT I have data like

  • Sample1
  • Sample2
  • Sample3

I am using FileName.DAT to read content of FileNames.

If multiple files exist as in this case Sample1 , I want to select older one , i.e. Sample1_20091231

So in this case I want to select Sample1_20091231,Sample2_20100115,Sample3_20100115 and neglect
Sample1_20100110,Sample1_20100115.

How to implement it ?

Any Suggestions.

$ ls Sam* |sort |awk -F "_" '!a[$1]++ {print $0}'
Sample1_20091231
Sample2_20100115
Sample3_20100115

Thanks Dost:D

That one-liner worked gr8 for me:b:

KUDOS !!!:slight_smile:

UNIX FORUMS ROCK!!!:D:b:;):):cool:

---------- Post updated at 02:52 PM ---------- Previous update was at 11:34 AM ----------

Hi

I am using this code.

 
#!/bin/ksh
while read line
do
ls $line |sort |awk -F "_" '!a[$1]++ {print $0}'
done<filename.DAT>fileselected.DAT

However if $line has some value Say 'ABC*' and there no file exist as ABC* then it will prompt error, I want to save an entry for those files also by displaying $line.

eg: Content in filename.DAT

  1. Sample1
  2. Sample2
  3. ABC1
  4. Sample3

Files in folder are :

  1. Sample1_20091231
  2. Sample1_20100120
  3. Sample2_20100120
  4. Sample3_20100120

Using the above code I am getting :

  1. Sample1_20091231
  2. Sample2_20100120
  3. Sample3_20100120

But there is no entry for ABC1.

Output required is

  1. Sample1_20091231
  2. Sample2_20100120
  3. ABC1
  4. Sample3_20100120

Help me with this !!!

Maybe something like this?

#!/bin/ksh

while read line
do
  ls $line* > /dev/null 2>&1
  if [ $? -ne 0 ]; then
    echo "$line"
  else
    ls $line* |sort |awk -F "_" '!a[$1]++ {print $0}'
  fi
done < filename.DAT > fileselected.DAT

Thanks MITRA:D

UNIX FORUMS ROCKKKK:b::cool::):D;)

Another alternative:

while read f; do
   set "$f"*
   [ -e "$1" ] && f=$1
   echo "$f"
done < filename.DAT > fileselected.DAT

Read a line from filename.DAT and use it as the basis for a glob. If there is a match, the shell expands the glob in the set command and replaces it with an already sorted list, which given the format of the filenames will place the oldest in $1. If there is no match, $1 will contain the unexpanded glob. We then check to see if $1 exists to decide what to echo.

Note: Simply comparing "$f"* to "$1" would probably work in this case, given the constrained filename format, but in general it could fail since it would be possible for there to be a file whose name is identical to the pattern it matches: f* could expand to match a file whose name is f*.

Regards,
Alister