moises chin
moises chin

Reputation: 33

How to remove all parts of a filename after the first dot on mac

I'm trying to do this on the mac terminal

I want to strip all the fields after the first dot on a filename but keep the extension at the end, and there can be an arbitrary length of dots.

Input:

file1.some.stuff.mp3 file2.other.stuff.stuff.mp3 file3.some.thing.mp3 file4.one.two.three.four.mp3

Expected output:

file1.mp3 file2.mp3 file3.mp3 file4.mp3

I have all the files on the same folder.

Upvotes: 3

Views: 1202

Answers (3)

Riz
Riz

Reputation: 1167

for i in `ls *.mp3`; do NAMES=`echo $i|cut -d. -f1`; mv "$i" "$NAMES.mp3"; done

Upvotes: 0

dibery
dibery

Reputation: 3460

Using bash variable substitution you may achieve the following:

for i in file1.some.stuff.mp3 file2.other.stuff.stuff.mp3 file3.some.thing.mp3
do
  echo "${i/.*./.}"
done

${i/.*./.} means to replace .*. by .. That is, it will match .some.stuff. in file1.some.stuff.mp3 and .b.c.d. in a.b.c.d.e.

In the parameter expansion section of man bash:

${parameter/pattern/string} Pattern substitution. The pattern is expanded to produce a pattern just as in pathname expansion. Parameter is expanded and the longest match of pattern against its value is replaced with string.

Upvotes: 2

chepner
chepner

Reputation: 531095

As long as the filenames are guaranteed to have at least one . with non-empty strings preceding and following a ., this is a matter of simple parameter expansions.

for f in file1.some.stuff.mp3 file2.other.stuff.stuff.mp3 file3.some.thing.mp3 file4.one.two.three.four.mp3; do
    echo "${f%%.*}.${f##*.}"
done

produces

file1.mp3
file2.mp3
file3.mp3
file4.mp3

In the directory where the files exit, use something like

for f in *.mp3; do

to iterate over all MP3 files.

Upvotes: 4

Related Questions