2

I am trying to read files one by one by using the for loop like below, by passing argument to the functions. Argument 3 makes lot of problem due to space in file names.

Example:

source_file_restructure()
{

echo "inside the function"
source_folder=$1
target_folder=$2
file_pattern=$3
delimiter=$4


echo $file_pattern


echo " Getting inside the function.... "


for file_name in `ls -Al ${source_folder}*"${file_pattern}"*.csv`
do

some processing.......

done

The above ls command not working properly when there are files contain white spaces like file 1.csv,

Input :

SOurce Folder : /home/test/

File Pattern : "file"

Function argument : 
source_file_restructure ${source_folder} ${target_folder} "${file_pattern}" ${delimiter}

Suggest some option to handle the problem.

William R
  • 609

3 Answers3

3

Replace

for file_name in `ls -Al ${source_folder}*"${file_pattern}"*.csv`

With:

for file_name in "${source_folder}"*"${file_pattern}"*.csv

The output of a command in backticks, as in the first form above, is subject to word-splitting. The second form above does not use backticks. It will, by contrast, work with any file name, even ones that contain spaces, tabs, newlines or any other difficult character.

Also, replace

source_file_restructure ${source_folder} ${target_folder} "${file_pattern}" ${delimiter}

With

source_file_restructure "${source_folder}" "${target_folder}" "${file_pattern}" "${delimiter}"

Without the double-quotes, the shell will perform word-splitting. With the double-quotes, the function will be called correctly even if source_folder or target_folder have spaces, tabs, newlines, or other difficult characters.

John1024
  • 74,655
0

You have to set the following environment variable in first of your script:

IFS=$(echo -en "\n\b")
PersianGulf
  • 10,850
0

I used something like this in one of my scripts :

ls -Q "$folderToRead" | while read file # ls -Q puts every entry between quotes : "file".
do
    file=`echo $file | tr -d '"'` # This erases the quotes from the -Q argument, so you 
                                    # can work on the file without worrying about it.

Of course, you'd have to make it work in your script, by editing the ls command. I just wrote the short version.

Tangeek
  • 11