In a directory you have some various files - .txt
, .sh
and then plan files without a .foo
modifier.
If you ls
the directory:
blah.txt blah.sh blah blahs
How do I tell a for-loop to only use files without a .foo
modify? So "do stuff" on files blah and blahs in the above example.
The basic syntax is:
#!/bin/bash FILES=/home/shep/Desktop/test/* for f in $FILES do XYZ functions done
As you can see this effectively loops over everything in the directory. How can I exclude the .sh
, .txt
or any other modifier?
I have been playing with some if statements but I am really curious if I can select for those non modified files.
Also could someone tell me the proper jargon for these plain text files without .txt?
The syntax to loop through each file individually in a loop is: create a variable (f for file, for example). Then define the data set you want the variable to cycle through. In this case, cycle through all files in the current directory using the * wildcard character (the * wildcard matches everything).
To change directories, use the command cd followed by the name of the directory (e.g. cd downloads ). Then, you can print your current working directory again to check the new path.
#!/bin/bash FILES=/home/shep/Desktop/test/* for f in $FILES do if [[ "$f" != *\.* ]] then DO STUFF fi done
If you want it a little bit more complex, you can use the find-command.
For the current directory:
for i in `find . -type f -regex \.\\/[A-Za-z0-9]*` do WHAT U WANT DONE done
explanation:
find . -> starts find in the current dir -type f -> find only files -regex -> use a regular expression \.\\/[A-Za-z0-9]* -> thats the expression, this matches all files which starts with ./ (because we start in the current dir all files starts with this) and has only chars and numbers in the filename.
http://infofreund.de/bash-loop-through-files/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With