Reputation: 35
I've got the following "problem". I have a bunch of files (like thousands) named "ThisIsAFile-BLAH.txt", and I would like to clean these file names so that they're called only "ThisIsAFile.txt", removing everything after the "-" symbol including it.
What would be the best way to proceed?
Thanks in advance for your time and help.
P.S. OS is GNU/Linux. P.S. 2 I'm trying to teach myself how to automate menial tasks by writing simple scripts.
Solution:
Thanks guys. I finally got it.
rename 's/-[^-]*(?=\.\w+)$//' *.txt
Thanks again.
Upvotes: 1
Views: 1046
Reputation: 46843
If you don't have too many files, you can loop through your files with a glob:
for i in *-BLAH.txt; do
mv -nv -- "$i" "${i%-BLAH.txt}.txt"
done
(note the use of -n
so as to not overwrite an otherwise already existing file, the use of -v
so at to be verbose (optional) and the use of --
just in case one file starts with a hyphen, so as to not confuse mv
that would try to interpret it as options). Also not the quotings!
If you have lot of files, you can use find
, it might be quicker than Bash's globbing:
find . -maxdepth 1 -name '*-BLAH.txt' -exec bash -c 'while(($#)); do mv -nv -- "$1" "${1%-BLAH.txt}"; shift; done' _ {} +
Here I'm using find's +
operator so that the bash
command is not spawned too many times. Then bash does its loop on the arguments given by find. Note the use of the dummy argument _
since launched this way, Bash will set its positional arguments starting from 0, not from 1.
The find method is really good, as you can fine tune which files will you'll apply the bash loop to. Inside the bash loop, you can then generate whatever renaming scheme you like.
Upvotes: 0
Reputation: 733
by using awk it can be written as
input file:
ThisIsAFile2-Blah.txt
ThisIsAFile3-Blah.txt
ThisIsAFile-Blah.txt
command for changing
ls *.txt|awk `s=$1` 'BEGIN{FS="-"; OFS=""} {print "mv "$s" "$1,".txt"}' |sh
output of the same would be
ThisIsAFile2.txt
ThisIsAFile3.txt
ThisIsAFile.txt
Upvotes: 0
Reputation: 785406
Let's say:
s="ThisIsAFile-BLAH.txt"
Pure BASH:
echo "${s/-*\./.}"
ThisIsAFile.txt
Using sed:
sed 's/-.*\./\./' <<< "$s"
ThisIsAFile.txt
Upvotes: 1
Reputation: 300965
Check man rename
, see if supports regex. if it does, something as simple as this would do it
rename 's/-.*/.txt/' *.txt
That searches all .txt filenames for a dash, and replaces it and everything that follows with .txt
Upvotes: 1