Search code examples
linuxcommandline

Moving files with a certain extension using grep


I'm trying to move files with the .txt extension.

ls /original/file/path | grep .txt

This successfully lists the files with txt extension. However when I do the following:

mv `ls /original/file/path | grep .txt` /the/new/path

I get an error that says:

mv: cannot stat 'test.txt': No such file or directory

Is there any reason I'm running into this error?


Solution

  • for that I would use find:

     find /original/file/path/ -maxdepth 1 -name '*.txt'  -exec mv {} /the/new/path/ \;
    

    explaining the parameters:

    • look for files in /original/file/path/
    • only on the current folder (find will go deep in the tree if you want)
    • with the name *.txt
    • and execute the command mv replacing {} by each file found.