1

This has been driving me crazy...

I want to list files in a dir and, based on the number interate on all files except the latest one, here is the code snipplet


FILECOUNT=$(ls -lt [dir]*.log | grep -c .log )
for (( c=2; c<=$FILECOUNT; c++ ))
do
FILEDIR=$("ls -1t [dir]*.log | sed -n '$c p'")

I have been having issues with $c interpretation, the format above works but the sed command fails... although entering the last line of the log in the cli works like a charm


 FILECOUNT=24

(( c=2 ))

(( c<=24 ))

C is : 2

'ls -1t [dir]*.log | sed -n '''2 p''''

line 41: ls -1t [dir]*.log | sed -n '2 p': No such file or directory


any help would be greatly appreciated!

the [dir] is obviously a valid directory

AdminBee
  • 22,803
Jay
  • 13

1 Answers1

3

The primary issue you have is that you put everything in the command substitution in double-quotes:

FILEDIR=$("ls -1t [dir]*.log | sed -n '$c p'")

This would instruct the shell to locate an executable file with verbatim name ls -1t [dir]*.log | sed -n '$c p'" and no arguments, as opposed to executing the command ls with options -1t and operand [dir]*.log whose output is to be piped to the executable sed with option -n and argument '$c p'. Try to remove the double-quotes, as in

FILEDIR=$(ls -1t [dir]*.log | sed -n '$c p')

However then you will face the issue that the variable expansion is disabled in your single-quoted sed command. One recommended way is to break the single-quote argument and place the variable in a double-quoted interjection, as in

FILEDIR=$(ls -1t [dir]*.log | sed -n "$c"' p')

Also, I must issue the mandatory warning not to parse the output of ls. ;)

AdminBee
  • 22,803
  • 1
    @Jay You're welcome :) But as mentioned, you may want to look at methods that don't involve the output of ls for future applications - filenames can "legally" contain a lot of crazy characters, some of which (in particular spaces and newlines) will confuse your shell and lead to strange behavior. – AdminBee Jun 02 '21 at 13:16