Home > Mobile >  linux shell script to fetch a <latest file> of <particular name> in a folder
linux shell script to fetch a <latest file> of <particular name> in a folder

Time:12-15

I'm enhancing my linux script, I have a folder with lots of files of different dates, I want to fetch a latest file starting with a particular name.

For ex.
I have below list of files in a folder I need latest file of name Subnetwork_RAN in a folder:

Subnetwork_PCC_11Dec2022UTC0500
Subnetwork_RAN_12Dec2022UTC0500
Subnetwork_RAN_13Dec2022UTC0500
Subnetwork_PCC_13Dec2022UTC0500

Output will be file name Subnetwork_RAN_13Dec2022UTC0500

I tried to build a linux shell script to get latest file of particular name.

CodePudding user response:

Supposing you have a file called test.txt with the filenames you showed. Then you can do this:

awk 'BEGIN {FS="_"} $0 ~/Subnetwork_RAN/ {printf "%s ",$0; system("date  %s -d " $3)}' asd | sort -rn -k 2 | head -1 | cut -d " " -f 1

Output:

Subnetwork_RAN_13Dec2022UTC0500

Some explanation:

  • $0 ~ /Subnetwork_RAN/ matches all the lines containing the sub-string "Subnetwork_RAN"
  • The bash command date can recognize the date format like this 13Dec2022UTC0500 and transform it in a timestamp (date %s)
  • sort sorts numerically in reverse order based on the second field (timestamp output of awk system call)
  • head gives the first line, i.e., the most recent
  • cut takes only the first field given a field separator equal to " ". The first field is the full filename (printf call in awk)

CodePudding user response:

This problem has a rather simple awk solution:

ls -tl | awk ' $9 ~ /Subnetwork_RAN/ {print $9; exit;}'

ls -tl outputs a long listing of the current directory, sorted by time (newest first).

This output is piped to awk which (line-by-line) looks for a filename containing the required string. The first time it finds one, it prints the filename and exits.

Note, this assumes (as in your example) that the filename contains no white space. If it does, you need to modify the print statement to print the substring of the line $0 beginning with your string, to the end of the line.

If your string might be repeated in more recent filenames but not at the start, the regex condition can be modified to select only filenames where your string is at the start $9~/^Subnetwork_RAN/

  • Related