user5419230
user5419230

Reputation: 13

Trimming a part of file extension for all the files in directory - Linux

I have a requirement in which I want to trim the file extension for all the files contained in a directory: -

The file will be like;

America.gz:2170
Europe.gz:2172
Africa.gz:2170
Asia.gz:2172

what I need is to trim the :2170 and :2172 from all the files, so that only the .gz extension remains.

I know that with the help of below SED code, it is possible for all the entries in a file, however I need for all the files in a directory: -

**sed 's/:.*//' file**

Any bash or awk code to fix this will be highly appreciated.

Thanks in advance.

Upvotes: 1

Views: 101

Answers (3)

anubhava
anubhava

Reputation: 785731

You can do this in bash:

shopt -s nullglob
for f in *.gz:*; do
    mv -- "$f" "${f%:*}"
done

"${f%:*}" will remove everything after : on RHS of variable $f

Upvotes: 4

Avinash Raj
Avinash Raj

Reputation: 174806

You may use rename command.

rename 's/:.*//' *.gz:*

or

rename 's/:[^:]*$//' *.gz:*

Upvotes: 1

user4832408
user4832408

Reputation:

This entire job can be done with a for loop and the substring processing operator '%':

"${parameter%word} Remove Smallest Suffix Pattern."

#!/bin/sh

for i in *
do #mv "$i" "${i%:}"
   echo " mv $i ${i%:*}"
done

Upvotes: 0

Related Questions