1

I am running a command that I use to find the most recent file in a folder then grep the contents for a matching pattern. Here is the command flow that shows the problem I am having.

root@backup /]# grep -w 'sucessfully completed.' "$(ls -1rt /var/log/folder | tail -n1)"
/bin/grep: <file_name>: No such file or directory
[root@backup /]# cd /var/log/folder/
[root@backup file_folder]# grep -w 'sucessfully completed.' "$(ls -1rt /var/log/folder | tail -n1)"
sucessfully completed.

In the first command, it finds the file but then says no such file or directory. Weird. Then, as you can see I cd'd inside the actual folder ran the same command and it worked. My variable has the absolute path so what is going on here? I have checked for any grep aliases that could be interfering and found none. If I run the commands separately outside of using a variable it works and it works outside of the files folder. (as I would expect)

[root@backup /]# grep -w 'sucessfully completed' /var/log/folder/file
sucessfully completed.
  • your ls -1rt | tail -n1 only returned filename, not a full path. – cuongnv23 May 13 '16 at 13:49
3

dirname of file is missing in first part, try

grep -w 'sucessfully completed.' "/var/log/folder/$(ls -1rt /var/log/folder | tail -n1)"

do not try ... unles there is no dir in /var/log/folder/

grep -w 'sucessfully completed.' "$(ls -1rt /var/log/folder/* | tail -n1)"
  • Awesome. There was another dir inside the folder I was searching. – user53029 May 13 '16 at 13:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.