-2

I have some files like that:

my_file_210804_2056_856.csv_20210804170806
my_file_210804_2056_856.csv_20211119181137
my_file_210805_2056_857.csv_20210805200847
my_file_210805_2056_857.csv_20211119181137
      ...

I want to retrieve the last version of the file by a unix command.

For example for the file 210804 I want to retrieve only my_file_210804_2056_856.csv_20211119181137 because it's the last.

Aserre
  • 4,916
  • 5
  • 33
  • 56
DiR95
  • 49
  • 7
  • 1
    What have you tried so far ? please show your atempt and edit it in the question. – Aserre Jan 26 '22 at 07:37
  • Also, how do you know which one is last ? For instance, imagine you have `my_file_210804_2056_856.csv_20211119181137` and `my_file_210804_2057_857.csv_20210804170806`. Which part is taken for the comparison ? The `2056` or the `20211119181137` ? – Aserre Jan 26 '22 at 07:37
  • I can't have this case. I have only one file per day with different timestamp – DiR95 Jan 26 '22 at 08:01

1 Answers1

0

You can use hashes in Bash.

#! /bin/bash

exec <<EOF
my_file_210804_2056_856.csv_20210804170806
my_file_210804_2056_856.csv_20211119181137
my_file_210805_2056_857.csv_20210805200847
my_file_210805_2056_857.csv_20211119181137
EOF

declare -A files
while read -r line; do
  if [[ $line =~ (.*csv)_(.*) ]]; then
    if [[ ${files[${BASH_REMATCH[1]}]} < ${BASH_REMATCH[2]} ]]; then
      files[${BASH_REMATCH[1]}]=${BASH_REMATCH[2]}
    fi
  fi
done
for name in "${!files[@]}"; do
  printf '%s_%s\n' "$name" "${files[$name]}"
done

declare -A declares a hash. read -r line reads a line. The while loop does this until nothing is left. [[ $line =~ (.*csv)_(.*) ]] compares the line read with a regular expression and captures the parts before and after the underline between the extension and the time stamp in the array BASH_REMATCH. The if condition checks, if the already stored value is lower then the new value. Non existing values are zero. If the value is small, the hash gets updated with the current value. The for loop iterates over the hash and reconstructs the remaining file names.

ceving
  • 21,900
  • 13
  • 104
  • 178