Copy files from multiple folders with including folder name in Linux - linux

I have multiple sub folders e.g.:
ls ./
F1 F2 F5 F8 F12 ...
Each folder contain file "file.txt"
How to copy all file.txt files to main folder containing folder name?
cp ./F1/file.txt ./file_1.txt
cp ./F2/file.txt ./file_2.txt
...

Perl One Liner
first go to main folder than:
find . | perl -a -F/ -lne 'qx(cp -r "$F[1]" T/ )'
note
do not worry about log file on the screen if would be!
T/
is your target directory
main folder
Where all your file exist. If your all file is in the folder Music for example; so cd Music then that Perl One Liner

declare -a dirs
i=1
for d in */
do
dirs[i++]="${d%/}"
done
echo "There are ${#dirs[#]} dirs in the current path"
for((i=1;i<=${#dirs[#]};i++))
do
echo "Copying file.txt from ${dirs[i]} dir..."
cp ./${dirs[i]}/file.txt ./file_$i.txt
done
Save it as a script file, fileTxtCopy.sh, for instance. Then place it at the parent dir and give it executable permission sudo chmod +x fileTxtCopy.sh.
Run it as script and you should have all your file.txt file copied in parent dir.

Copies file.txt files from each folder inside a current directory to the current directory and appends numbers contained in a folder name to the name of the copied file.
for i in *; do a=$(<<< "$i" grep -o "[0-9]*" -); cp "$i/file.txt" "file_$a.txt"; done
Not the most robust approach though.

Related

Prevent mkdir -p from overwriting directories and cp from overwriting files

I have a shell script and I want to use it for making directories and files in those direcctories. It is extremely important that this script does not overwrite or delete any files or directories. So I want to make a directory which is one directory above from the directory where the script is in. In this directory I want to make two subdirectories and in one of the subdirectories I want to copy 2 pre-existing files that have some text in them.
Files file1 and file2 are always going to be in same directory as this script and they always have same contents in them and it is very important that the contents do not change. I have multiple structures like this, they just have different names.
So I tried this:
#! /bin/bash
echo "Enter directory name"
read dirname
mkdir -p ../$dirname/{dir1,dir2}
cp file1 file2 ../$dirname/dir2
But if dirname already exists, this script overwrites it and also overwrites all the contents in it. Then I tried this:
#! /bin/bash
echo "Enter directory name"
read dirname
if [ -d $dirname ]
then
echo "directory already exists"
else
mkdir -p ../$dirname/{dir1,dir2}
cp file1 file2 ../$dirname/dir2
fi
But also this script overwrites everything. How can I make this script so that if dirname already exists, the script does not create new directories and it does not copy any files in any directory, i.e. it does not do anything?

Create subfolder with same name as parent and move files into it

I have folders as below. I want to create subdirectory with same name and move only few of the files into sub directory
Input
Parent
folder1/a.txt
folder1/b.txt
folder2/a.txt
folder2/b.txt
folder3/a.txt
folder3/b.txt
Output
Parent
folder1/folder1/a.txt
folder1/b.txt
folder2/folder2/a.txt
folder2/b.txt
folder3/folder3/a.txt
folder3/b.txt
I tried this , but this is working only for files not folders
for file in *; do dir=$(echo $file | cut -d. -f1); mkdir -p $dir; mv $file $dir; done
If your shell is bash, you can run the following:
for file in */a.txt ; do
dir=${file%/a.txt}
mkdir "$dir/$dir"
mv "$file" "$dir/$dir"
done
It uses the parameter expansion to remove the /a.txt from the file name which only leaves the directory name in $dir.

Linux Bash: Move multiple different files into same directory

As a rather novice Linux user, I can't seem to find how to do this.
I am trying to move unique files all in one directory into another directory.
Example:
$ ls
vehicle car.txt bicycle.txt airplane.html train.docx (more files)
I want car.txt, bicycle.txt, airplane.html, and train.docx inside vehicle.
Right now I do this by moving the files individually:
$ mv car.txt vehicle
$ mv bicycle.txt vehicle
...
How can I do this in one line?
You can do
mv car.txt bicycle.txt vehicle/
(Note that the / above is unnecessary, I include it merely to ensure that vehicle is a directory.)
You can test this as follows:
cd #Move to home directory
mkdir temp #Make a temporary directory
touch a b c d #Make test (empty) files ('touch' also updates the modification date of an existing file to the current time)
ls #Verify everything is there
mv a b c d temp/ #Move files into temp
ls #See? They are gone.
ls temp/ #Oh, there they are!
rm -rf temp/ #DESTROY (Be very, very careful with this command)
Shorthand command to move all .txt file
You can try using a wildcard. In the code below, * will match all the files which have any name ending with .txt or .docx, and move them to the vehicle folder.
mv *.txt *.docx vehicle/
If you want to move specific files to a directory
mv car.txt bicycle.txt vehicle/
Edit: As mentioned in a comment, If you are moving files by hand, I suggest using mv -i ... which will warn you in case the destination file already exists, giving you a choice of not overwriting it. Other 'file destroyer' commands like cp & rm too have a -i option
mv command in linux allow us to move more than one file into another directory. All you have to do is write the name of each file you want to move, seperated by a space.
Following command will help you:
mv car.txt bicycle.txt airplane.html train.docx vehicle
or
mv car.txt bicycle.txt airplane.html train.docx vehicle/
both of them will work.
You can move multiple files to a specific directory by using mv command.
In your scenario it can be done by,
mv car.txt bicycle.txt airplane.html train.docx vehicle/
The point you must note is that the last entry is the destination and rest everything except mv is source.
One another scenario is that the destination is not present in our directory,then we must opt for absolute path in place of vehicles/.
Note: Absolute path always starts from / ,which means we are traversing from root directory.
I have written a small bash script that will move multiple files(matched using pattern) present in multiple directories(matched using pattern) to a single location using mv and find command in bash
#!/bin/bash
for i in $(find /path/info/*/*.fna -type f) # find files and return their path
do
mv -iv $i -t ~/path/to/destination/directory # move files
done
$() is for command substitution(in other words it expand the expression inside it)
/*/ wild card for matching any directory, you can replace this with any wild card expression
*.fna is for finding any file with.fna extension
-type f is for getting the full path info of the located file
-i in mv is for prompt before overwrite( extra caution in case the wild card exp was wrong)
-v for verbose
-t for destination
NOTE: the above flags are not mandatory
Hope this helps

Linux: How to move files with same name, diff ext. into their own folder?

I have files like this
This list is a sample of my files note the actual files are not in sucessive order.
file1.a
file2.a
file1.b
file2.b
...
and some have a .c extension but not all
How would I move these files into their own named folder.
I have tried this
find . -type f -print0 | xargs -0 -l sh -c 'mkdir "${1%.*}" && mv "$1" "${1%.*}"' sh
but it doesn't work as intended i.e. Well it creates the folders but wont put the second file of same name different extension in the same folder.
mkdir: cannot create directory ‘./file1’: File exists
mkdir: cannot create directory ‘./file2’: File exists
mkdir: cannot create directory ‘./file3’: File exists
You should use mkdir -p, it won't complain (and break the &&) if directories exist (it will also create parent directories if those don't exist).
for FILE in $(ls file[0-9].[a-z])
do
DIRNAME=$(echo $FILE |cut -c1-5)
[ -d $DIRNAME ] || mkdir $DIRNAME
mv ${FILE}* $DIRNAME
done
This will give you:
$ ls file1 file2
file1:
file1.a file1.b file1.c
file2:
file2.a file2.b file2.c

./mv.sh: line 4: cd: 1.4-1.5.csh: Not a directory

I want to move file1 to directory1 in many subdirectories of current directory. Both file1 and directory1 are in each subdirectory. I write the following script in current directory but it reports "./mv.sh: line 4: cd: directory1: No such file or directory". Actually, the directory1 is in each subdirectory.
1 #!/bin/bash
2
3 for i in *; do
4 builtin cd $i
5 mv file1 directory1
6 builtin cd ..
7 done
error
./mv.sh: line 4: cd: directory1: No such file or directory
mv: cannot stat `file1': No such file or directory
Is it possible that directory1 is a dangling symbolic link? For example:
mkdir foo
ln -s foo foolink
mv foo bar # foolink still points to foo but foo is gone!
cd foolink
# bash: cd: foolink: No such file or directory
Also, instead of
cd dir
mv foo subdir
cd ..
I would recommend the more succinct, and more importantly, safer version:
mv dir/foo dir/subdir/
Why is this safer? Imagine that dir doesn't exist:
cd dir # Fails
mv foo subdir # Oops! Now we're trying to move a file from the current directory
cd .. # Even bigger oops! Now we're even higher in the directory tree,
# and on the next iteration will be moving files around that we
# shouldn't be
(You could also avert this issue in this particular case by using set -o errexit but in general cd .. in scripts is dangerous, in my opinion.)
Also, as Ansgar Wiechers said, you should use find instead of trying to crawl the tree yourself.
I'd use find rather than trying to crawl the directory tree:
find . -type f -name "file1" -execdir mv {} directory1/ \;
This assumes that each directory with a file file1 has a subdirectory directory1.
I suppose the cd .. in line 6 lead you to another directory. You can check this by inserting builtin pwd between lines 6 and 7. This shows you in which directory you actually are after the cd ...
Maybe one of the directories is in fact a link to another directory? This could be the reason for landing somewhere you did not expect.
If the cd $i fails, you could also land in a wrong directory, this may happen if $i is not a directory or you don't have permission to explore it.

Resources