-1

lets say I want to copy a list of files to another directory

-rw-rw----    Sep 1 11:06   File1.txt
-rw-rw----    Sep 1 11:06   File101.txt
-rw-rw----    Sep 3 11:06   File2.txt    
-rw-rw----    Sep 4 11:06   File303.txt  

I would like to grep all the files that have a Sep 1 in there

ls -lrt | grep 'Sep 1'

and try to pass it to cp as an argument

cp `ls -lrt | grep 'Sep 1'` /directory/
or
cp $(ls -lrt | grep 'Sep 1') /directory/

with the second option i that is an illegal variable name can you please help me with this?

Rubenex
  • 469
  • 2
  • 8
  • 23

1 Answers1

4

Do not parse the output of ls: Why you shouldn't parse the output of ls.

Instead, you can do something like:

cp *1* /directory/

This *1* will match anything containing 1 and will apply to the cp command, so that it will be expanded to something like:

cp File1.txt File2.txt File303.txt File101.txt /directory/

Update

The first solution would be do to the following: print the file name after grepping of those files whose modification time is Sep 1. Based on that output, copy:

cp $(ls -1 | awk '/Sep 1/{print $NF}') /directory/

But this is very fragile, because filenames with spaces won't be copied, as well as the general fact that parsing ls is a bad idea.

Instead, if you want to move files that were modified on last 24 hours, you can do this:

find . -maxdepth 1 -type f -mtime -1 -exec cp {} /directory/ \;
       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^
       performs the search           copies the matches to the dir

Or also add -daystart to match "created today", not last 24 hours: find . -maxdepth 1 -type f -daystart -mtime -1 ...

fedorqui
  • 275,237
  • 103
  • 548
  • 598