LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Using ls and renaming...... HELP (https://www.linuxquestions.org/questions/linux-newbie-8/using-ls-and-renaming-help-792716/)

Drigo 03-02-2010 04:28 PM

Using ls and renaming...... HELP
 
ok...I wanted to rename files in subdirectories using a simple bash script. Here is what I have so far:

for FILE in $(find ./ -name PDI_*); #any other commands helpful for this?
?? Something elsE? #do mv $FILE "${FILE//PDI_11420_}" ;

done


Here is a simple example of what I want to do. Basically here add NewText_ to all the files in the subdirectories with extension *.nii:


Input:

Parent_directory
Subdirectory_A
File1.nii
File2.nii
File3.nii
File4.nii
other.xxx
Subdirectory_B
File1.nii
File2.nii
File3.nii
File4.nii
othera.yyy
Subdirectory_C
File1.nii
File2.nii
File3.nii
File4.nii
.
.
.


What I want (output):


Parent_directory
Subdirectory_A
NewText_File1.nii
NewText_File2.nii
NewText_File3.nii
NewText_File4.nii
Subdirectory_B
NewText_File1.nii
NewText_File2.nii
NewText_File3.nii
NewText_File4.nii
Subdirectory_C
NewText_File1.nii
NewText_File2.nii
NewText_File3.nii
NewText_File4.nii

irmin 03-02-2010 04:39 PM

What's about this?
Code:

find -name "*.nii" | while read name; do mv $name `dirname "$name"`/NewText_`basename $name`; done
Using $(...) if you expect large output from ... is not a good idea in general, because it will make your command very long and eventually exceed the max. command line length.

Drigo 03-03-2010 09:34 AM

Thank you...it did the trick@!
I am assuming 'dirname and 'basename are built-in strings right? I would like to understan a little bit the code so I can play around with it in different files that I have.

irmin 03-03-2010 04:52 PM

dirname and basename are coreutilitities:
see dirname(1) and basename(1) for details.

Here's a summary:

dirname returns the directory of its argument:
dirname /bin/ls => /bin
dirname ../../abc/def => ../../abc

basename the actual filename with the directory stripped off
basename /bin/ls => ls
basename ../../abc/def => def

Now to the code:
find -name "*.nii" will write all files matching the pattern to stdout
this output is read in the while loop with read line by line, where each line is stored in name.

For each name mv will be called with original filename and the modified filename.

I hope this helps.


All times are GMT -5. The time now is 10:48 PM.