passing filenames in current directory as arguments to other function
Hello,
I want to list files with certain extension in current directory and then pass each one of them as input argument to another function in the script (preferably after some string trimming operations in future). I wrote following test script: Code:
#!/bin/bash Code:
[ssr@localhost Aim01]$ ./test2.sh 1) to point out mistake causing for loop "bad substitution" error 2) to be able to pass each filename individually as argument to myPrintf() function ? 3) suggest reference for trimming file extension from name or picking up just one word e.g. U*** to give U038 above fourth file (unlike here, that U*** pattern is present in all files with specified extension in list ) ? Thanks, |
To iterate through the files with a common extension in the current directory you can use a construction like:
Code:
for Filename in *.sh; do Code:
echo "First four letters: "${Filename:0:4} Code:
#!/bin/bash |
In addition:
Code:
FileList=`find . -name \*$extn` For trivial, single directory level matches, you can use simple globbing. Code:
FileList=( *."$extn" ) Code:
shopt -s globstar For more complex matches, including recursive matching, you can use find, but you need to be careful to do it in a way that handles unusual filenames correctly. This generally involves the -print0 option. Code:
while IFS='' read -r -d '' ; do http://mywiki.wooledge.org/BashFAQ/001 http://mywiki.wooledge.org/BashFAQ/020 http://mywiki.wooledge.org/UsingFind And to use the array, call it using the "@" symbol, with the whole thing in double-quotes. This ensures that each entry will be expanded as a separate string. Code:
printf '%s\n' "${FileList[@]}" BTW: $(..) is highly recommended over `..` |
It works now ...
Thank you David_the_H and allend.
I could get this problem sorted out using your suggestions. :) Here is my final code and its output - Code: Code:
#!/bin/bash OUTPUT: Code:
[ssr@localhost Aim01]$ ls *sh |
Good work!
But nah, arrays are actually one of the most overlooked of scripting features. You'd be surprised how many times posters have tried to cobble together oddball solutions when a simple array is all they really needed. Of course, you do need to ensure that you're using a shell that supports them, like bash or ksh. POSIX-based and older shells do not. |
All times are GMT -5. The time now is 11:10 PM. |