5

I need to move the files of a directory to another directory.I get stat error when I used the following program.

for i in dir1/*.txt_dir; do
mv $i/*.txt  dir2/`basename $i`.txt
done

error message

mv: cannot stat `dir1/aa7.txt_dir/*.txt': No such file or directory
charlie
  • 75
  • 1
  • 2
  • 5

4 Answers4

7

Normally, when a glob which does not match any filenames is expanded, it remains unchanged. Thus, you get results like this:

$ rm .bak rm: cannot remove `.bak': No such file or directory

To avoid this we need to change the default value of nullglob variable.

    #BASH

    shopt -s nullglob

    for i in dir1/*.txt_dir; do
       mv $i/*.txt  dir2/'basename $i'.txt
    done

Read more about it here: http://mywiki.wooledge.org/NullGlob

Hope this helps!

sushant-hiray
  • 1,838
  • 2
  • 21
  • 28
4
mv $i/*.txt  dir2/`basename $i`.txt

This doesn't work when there are no text files in $i/. The shell passes the raw string "$i/*.txt" to mv with the unexpanded * in it, which mv chokes on.

Try something like this:

for i in dir1/*.txt_dir; do
    find $i -name '*.txt' -exec mv {} dir2/`basename $i`.txt \;
done
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • Thank you very much for your answer. Actually there are text files in $i/. But still same error. – charlie Oct 05 '12 at 03:44
0

when you put directory/* alone in for iteration, it list each file with absolute path. use `ls

for i in ls dir1/*.txt_dir ; do

ms_guruvai
  • 31
  • 1
  • 2
-1

Whilst it is not shown in your example - using the correct quotes is important. in BASH "*" evaluates to * and '*' evaluates to the expansion glob. so

`ls *`

will show all files in directory and

`ls "*"`

will show all files named the literal *