Reputation: 364
Suppose a particular command generates few files (I dont know the name of these files). I want to move those files into a new folder. How to do it in shell script?
i can't use :
#!/bin/bash
mkdir newfolder
command
mv * newfolder
as the cwd contains lot of other files as well.
Upvotes: 0
Views: 11939
Reputation: 6866
Assuming that your command prints out names with one per line, this script will work.
my_command | xargs -I {} mv -t "$dest_dir" {}
Upvotes: 1
Reputation: 32697
If you'd like to move them into a sub-folder:
mv `find . -type f -maxdepth 1` newfolder
Setting a -maxdepth 1
will only find the files in the current directory and will not recurse. Passing in -type f
means "find all files" ("d" would, respectively, mean "find all directories").
Upvotes: 1
Reputation: 193814
The first question is can you just run command
with newfolder
as the current directory to generate the files in the right place it begin with:
mkdir newfolder
cd newfolder
command
Or if command
is not in the path:
mkdir newfolder
cd newfolder
../command
If you can't do this then you'll need to capture lists of before and after files and compare. An inelegant way of doing this would be as follows:
# Make sure before.txt is in the before list so it isn't in the list of new files
touch before.txt
# Capture the files before the command
ls -1 > before.txt
# Run the command
command
# Capture the list of files after
ls -1 > after.txt
# Use diff to compare the lists, only printing new entries
NEWFILES=`diff --old-line-format="" --unchanged-line-format="" --new-line-format="%l " before.txt after.txt`
# Remove our temporary files
rm before.txt after.txt
# Move the files to the new folder
mkdir newfolder
mv $NEWFILES newfolder
Upvotes: 4
Reputation: 5157
use pattern matching:
$ ls *.jpg # List all JPEG files
$ ls ?.jpg # List JPEG files with 1 char names (eg a.jpg, 1.jpg)
$ rm [A-Z]*.jpg # Remove JPEG files that start with a capital letter
Example shamelessly taken from here where you can find some more useful information about it.
Upvotes: 1