Reputation: 8473
I have a folder "model" with files named like:
a_EmployeeData
a_TableData
b_TestData
b_TestModel
I basically need to drop the underscore and make them:
aEmployeeData
aTableData
bTestData
bTestModel
Is there away in the Unix Command Line to do so?
Upvotes: 5
Views: 14046
Reputation: 319
Use the global flag /g
with your replace pattern to replace all occurrences within the filename.
find . -type f -print0 | xargs -0 rename 's/_//g'
Or if you want underscores replaced with spaces then use this:
find . -type f -print0 | xargs -0 rename 's/_/ /g'
If you like to live dangerously add the force flag -f
in front of your replace pattern rename -f 's/_//g'
Upvotes: 0
Reputation: 33159
I had the same problem on my machine, but the filenames had more than one underscore. I used rename
with the g
option so that all underscores get removed:
find model/ -maxdepth 1 -type f | rename 's/_//g'
Or if there are no subdirectories, just
rename 's/_//g'
If you don't have rename
, see Jaypal Singh's answer.
Upvotes: 0
Reputation: 6259
In zsh:
autoload zmv # in ~/.zshrc
cd model && zmv '(**/)(*)' '$1${2//_}'
Upvotes: 1
Reputation: 49
for f in model/* ; do mv "$f" `echo "$f" | sed 's/_//g'` ; done
Edit: modified a few things thanks to suggestions by others, but I'm afraid my code is still bad for strange filenames.
Upvotes: 3
Reputation: 30863
This will correctly process files containing odd characters like spaces or even newlines and should work on any Unix / Linux distribution being only based on POSIX syntax.
find model -type f -name "*_*" -exec sh -c 'd=$(dirname "$1"); mv "$1" "$d/$(basename "$1" | tr -d _)"' sh {} \;
Here is what it does:
For each file (not directory) containing an underscore in its name under the model directory and its subdirectories, rename the file in place with all the underscores stripped out.
Upvotes: 5
Reputation: 63974
maybe this:
find model -name "*_*" -type f -maxdepth 1 -print | sed -e 'p;s/_//g' | xargs -n2 echo mv
Decomposition:
plain files
in the directory model
what contains at least one underscore, and don't search subdirectoriessed
make filename adjustments - replace the _
with nothingxargs
what will rename the files with mv
The above is for a dry-run. When satisfied, remove the echo
before mv
for actual rename.
Warning: Will not work if filename contains spaces. If you have GNU sed
you can
find . -name "*_*" -maxdepth 1 -print0 | sed -z 'p;s/_//g' | xargs -0 -n2 echo mv
and will works with a filenames with spaces too...
Upvotes: 1
Reputation: 77185
You can do this simply with bash
.
for file in /path/to/model/*; do
mv "$file" "${file/_/}"
done
If you have rename
command available then simply do
rename 's/_//' /path/to/model/*
Upvotes: 7