0

I have a bash script that saves a date (of last change), filename, maybe number of changes etc in a file (something similar to ls output).

Is there any way to search in this file in bash, eg. get the most used file or the most recent file, but just the filename?

So the file looks something like this:

    2018-03-28 19:47:41   filename1
    2018-03-28 19:49:24   filename2
    2018-03-28 19:50:14   filename1
    2018-03-28 19:50:17   filename3

Now I would like to get the file that was used last, so I shall sort it (it's actually sorted already), but I only want to get the filename of the file last edited (with the latest date). Is there a way to do this apart from regex?

mamlask
  • 13
  • 2
  • 2
    Welcome to SO, please post samples in code tags in your post and let us know on same, without samples it is quite difficult for us to get clear picture of question. – RavinderSingh13 Mar 28 '18 at 18:03
  • use [sqlite](https://www.sqlite.org/index.html) and then you will be able to query whatever you want from your script – Diego Torres Milano Mar 28 '18 at 18:18
  • Welcome to the site! Check out the [tour](https://stackoverflow.com/tour) and the [how-to-ask page](https://stackoverflow.com/help/how-to-ask) for more about asking questions that will attract quality answers. You can [edit your question](https://stackoverflow.com/posts/49541278/edit) to include more information, e.g., as @RavinderSingh13 noted. – cxw Mar 28 '18 at 18:39

1 Answers1

0

If I understand you correctly:

head -1 foo.txt | tr -s ' ' | cut -d ' ' -f 3     # First line of foo.txt, only the filename
tail -1 foo.txt | tr -s ' ' | cut -d ' ' -f 3     # Last line 

will give you the lines you want (thanks to this). If foo.txt is already sorted, those will be the earliest and latest.

To store those in variables:

firstfn="$(head -1 foo.txt | tr -s ' ' | cut -d ' ' -f 3)"
echo "First filename is $firstfn"     # just a test
lastfn="$(tail -1 foo.txt | tr -s ' ' | cut -d ' ' -f 3)"

If you have awk, you can do this more simply (thanks to this answer):

awk -- 'END { print $3; }' foo.txt

for the last line, or

awk -- '{ print $3; exit }' foo.txt

for the first line. Same deal with the variables, e.g.,

firstfn="$(awk -- '{ print $3; exit }' foo.txt)"
cxw
  • 16,685
  • 2
  • 45
  • 81