Peter S
Peter S

Reputation: 575

OSX Terminal delete last 7 Characters of Filename

Hi is there an easy way to rename a bunch of files like:

A_16-25-55-313.txt

and

B_16-25-55-313.txt

so that all the Files in the Folder look like:

A_16-25.txt

and

B_16-25.txt

In this example case I would have to get rid of the last 7 Characters before the extension. I used the OS X terminal and tried stuff like:

for i in *.txt do set fName==$i
do mv $fName $fName:~0,-7.txt

which didn't work and:

for i in *
do
j=`echo $i | sed -e ’s/.......$//‘`
mv $i $j
done

which did not work as well.

Upvotes: 0

Views: 1726

Answers (1)

chepner
chepner

Reputation: 531125

Not sure what reference you are using for bash, but the following is what you want:

for i in *.txt; do
    # Get the filename minus the .txt suffix 
    drop_ext=${i%.txt}
    # Drop the last seven characters, then readd the suffix
    fName=${drop_ext%???????}.txt
    mv "$i" "$fName"
done

Actually, given that you know the suffix is 4 characters, you can just drop the last 11 characters right away before adding the suffix back.

for i in *.txt; do
    mv "$i" "${i%???????????}.txt"
done

Upvotes: 1

Related Questions