Iterate over a list of files with spaces

前端 未结 11 1672
-上瘾入骨i
-上瘾入骨i 2020-11-22 05:16

I want to iterate over a list of files. This list is the result of a find command, so I came up with:

getlist() {
  for f in $(find . -iname \"f         


        
11条回答
  •  庸人自扰
    2020-11-22 05:56

    Ok - my first post on Stack Overflow!

    Though my problems with this have always been in csh not bash the solution I present will, I'm sure, work in both. The issue is with the shell's interpretation of the "ls" returns. We can remove "ls" from the problem by simply using the shell expansion of the * wildcard - but this gives a "no match" error if there are no files in the current (or specified folder) - to get around this we simply extend the expansion to include dot-files thus: * .* - this will always yield results since the files . and .. will always be present. So in csh we can use this construct ...

    foreach file (* .*)
       echo $file
    end
    

    if you want to filter out the standard dot-files then that is easy enough ...

    foreach file (* .*)
       if ("$file" == .) continue
       if ("file" == ..) continue
       echo $file
    end
    

    The code in the first post on this thread would be written thus:-

    getlist() {
      for f in $(* .*)
      do
        echo "File found: $f"
        # do something useful
      done
    }
    

    Hope this helps!

提交回复
热议问题