Thursday, May 2, 2024
9
rated 0 times [  9] [ 0]  / answers: 1 / hits: 3609  / 2 Years ago, sun, may 15, 2022, 9:38:17

I have multiple files in one folder:



ABA.xy
BEB.xy
ACA.xy


The same files with different extension in another folder



ABA.rr
BEB.rr
ACA.rr


Then I have single folder for each file name



ABA
BEB
ACA


I would like to do the following. if the file with extension .xy and .rr have the same name as the folder, move to that folder.
For example



ABA.xy and ABA.rr in ABA


I am familiar with mv but I think that here I have to write a small script to do that.


More From » command-line

 Answers
2

Assuming your files stored in source dir and your target folders are in dest like following tree:



$ tree source
source
├── dir1
│ ├── ABA.xy
│ ├── ACA.xy
│ └── BEB.xy
└── dir2
├── ABA.rr
├── ACA.rr
└── BEB.rr
2 directories, 6 files

$ tree dest
dest
├── ABA
├── ACA
└── BEB
3 directories, 0 files


The command would be:



find source -type f -exec sh -c 'noext="${0%.*}"; echo mv '{}' "dest/${noext##*/}/"' {} ;



  • the source is the source directory or specify the parent directory.

  • noext="${0%.*}" strips the files extension and saves the result into noext variable.

  • "${noext##*/}" removes the file path portion from noext variable and pickup the only file name.


  • dest directory is destination parent directory.


  • So mv '{}' "dest/${noext##*/}/"' moves the current file to dest/$noext directory.



    The content of noext in above command is only filename without extension and path in it that specify the destination directory which is the same name as the current file name.




Here is a sample test that show the result of command



Note that this commands used echo for testing and dry run. If you ensure about what you are do, remove the echo in front of mv command to perform actual moving.


[#21499] Sunday, May 15, 2022, 2 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
naldis

Total Points: 257
Total Questions: 101
Total Answers: 111

Location: Kenya
Member since Sat, Feb 25, 2023
1 Year ago
;