Loop and iterating question

AIM: Want to run a shell command on all the .jl files
PROBLEM: how can i create a loop to iterate over unknown number of elements and run the shell command on them. I want it to be independent of number of files in directory.

const cmd1  = "ls"
const cmd2  = "-lh"
const cmd3  = "--color=auto"


function find_size()
    const myfile = "/home/arnuld/Templates/file.jl"
    run(`$cmd1 $cmd2 $cmd3 $myfile`)
end


find_size()

for i = 1:10
    run(`$cmd1 $cmd2 $cmd3 $i.jl`)
end

Does the following help?

help?> walkdir
search: walkdir

  walkdir(dir; topdown=true, follow_symlinks=false, onerror=throw)

  Return an iterator that walks the directory tree of a directory. The iterator returns a tuple containing (rootpath, dirs, files). The directory tree can be traversed top-down or bottom-up. If walkdir encounters a SystemError it will rethrow the error by default. A custom
  error handling function can be provided through onerror keyword argument. onerror is called with a SystemError as argument.

  for (root, dirs, files) in walkdir(".")
      println("Directories in $root")
      for dir in dirs
          println(joinpath(root, dir)) # path to directories
      end
      println("Files in $root")
      for file in files
          println(joinpath(root, file)) # path to files
      end
  end
2 Likes

Yeah. nice. I played with it and wrote this. It works. Thanks for the help :slight_smile:

# This program will iterate over all .jpg files in the given directory
# and tell their size

dirpath = "/home/arnuld/Pictures"

extensionName = ".jpg"
extensionSize = 4  # for .jpg has 4 characters: dot, j, p, g


function runShellCommand(str, sz)
    for(root, dirs, files) in walkdir(dirpath)
        println("Files in $root")
        for file in files
            s = joinpath(root, file)
            l = length(s)
            pos = l - sz + 1
            if s[pos:end] == str
                run(`ls -lh $s`)
            end
        end
    end
end


runShellCommand(extensionName, extensionSize)

Note that you can use splitext to get the file extension, so extensionSize is not needed in your case.

Cool :sunglasses: . Too many end statements though :expressionless:

# This program will iterate over all .jpg files in the given directory
# and tell their size

dirpath = "/home/arnuld/Pictures"

extensionName = ".jpg"

function runShellCommand(str)
    for(root, dirs, files) in walkdir(dirpath)
        println("Files in $root")
        for file in files
            s = joinpath(root, file)
            if(extensionName == splitext(s)[2])
                run(`ls -lh $s`)
            end
        end
    end
end

runShellCommand(extensionName)