0

I've read the answer here,but still got wrong. In my folder,I only want to deal with *.gz file,Windows 10.tar.gz got space in filename.

Assume the folder contain:

Windows 10.tar.gz Windows7.tar.gz otherfile

Here is my shell scripts,I tried everything to quote with "",still can't got what I want. crypt_import_xml.sh

#/bin/sh

rule_dir=/root/demo/rule
function crypt_import_xml()
{
    rule=$1
    # list the file in absoulte path
    for file in `ls ${rule}/*.gz`; do
        echo "${file}"
        #tar -xf *.gz

        #mv a b.xml to ab.xml

    done
}

crypt_import_xml ${rule_dir}

Here is what I got:

root@localhost.localdomain:[/root/demo]./crypt_import_xml.sh 
/root/demo/rule/Windows
10.tar.gz
/root/demo/rule/Windows7.tar.gz

After tar xf the *.gz file,the xml filename still contain space.It is a nightmare for me to deal with filename contain spaces.

Allan
  • 12,117
  • 3
  • 27
  • 51
J.Doe
  • 319
  • 1
  • 8

2 Answers2

4

You shouldn't use ls in for loop.

$ ls directory 
file.txt  'file with more spaces.txt'  'file with spaces.txt'

Using ls:

$ for file in `ls ./directory`; do echo "$file"; done
file.txt
file
with
more
spaces.txt
file
with
spaces.txt

Using file globbing:

$ for file in ./directory/*; do echo "$file"; done 
./directory/file.txt
./directory/file with more spaces.txt
./directory/file with spaces.txt

So:

for file in "$rule"/*.gz; do
    echo "$file"
    #tar -xf *.gz

    #mv a b.xml to ab.xml
done
alberand
  • 632
  • 5
  • 13
1

You do not need to call that ls command in the for loop, the file globbing will take place in your shell, without running this additional command:

XXX-macbookpro:testDir XXX$ ls -ltra
total 0
drwx------+ 123 XXX  XXX  3936 Feb 22 17:15 ..
-rw-r--r--    1 XXX  XXX     0 Feb 22 17:15 abc 123
drwxr-xr-x    3 XXX  XXX    96 Feb 22 17:15 .
XXX-macbookpro:testDir XXX$ rule=.
XXX-macbookpro:testDir XXX$ for f in "${rule}"/*; do echo "$f"; done
./abc 123

In your case you can change the "${rule}"/* into:

"${rule}"/*.gz;
Allan
  • 12,117
  • 3
  • 27
  • 51