nick
nick

Reputation: 241

How do I remove a specific extension from files recursively using a bash script

I'm trying to find a bash script that will recursively look for files with a .bx extension, and remove this extension. The filenames are in no particular format (some are hidden files with "." prefix, some have spaces in the name, etc.), and not all files have this extension.

I'm not sure how to find each file with the .bx extension (in and below my cwd) and remove it. Thanks for the help!

Upvotes: 10

Views: 13701

Answers (7)

ajaaskel
ajaaskel

Reputation: 1699

Extra: How to remove any extension from filenames

find -maxdepth 1 -type f | sed 's/.\///g'| grep -E [.] | while read file; do mv $file ${file%.*}; done

will cut starting from last dot, i.e. pet.cat.dog ---> pet.cat

find -maxdepth 1 -type f | sed 's/.\///g'| grep -E [.] | while read file; do mv $file ${file%%.*}; done

will cut starting from first dot, i.e. pet.cat.dog ---> pet

"-maxdepth 1" limits operation to current directory, "-type f" is used to select files only. Sed & grep combination is used to pick only filenames with dot. Number of percent signs in "mv" command will define actual cut point.

Upvotes: 1

gsbabil
gsbabil

Reputation: 7703

Here is another version which does the following:

  1. Finds out files based on $old_ext variable (right now set to .bx) in and below cwd, stores them in $files
  2. Replaces those files' extension to nothing (or something new depending on $new_ext variable, currently set to .xyz)

The script uses dirname and basename to find out file-path and file-name respectively.

#!/bin/bash

old_ext=".bx"
new_ext=".xyz"

files=$(find ./ -name "*${old_ext}")

for file in $files
do
    file_name=$(basename $file $old_ext)
    file_path=$(dirname $file)
    new_file=${file_path}/${file_name}${new_ext}

    #echo "$file --> $new_file"
    mv "$file"    "$new_file"
done

Upvotes: 1

tylerl
tylerl

Reputation: 30847

find . -name '*.bx' -type f | while read NAME ; do mv "${NAME}" "${NAME%.bx}" ; done

Upvotes: 27

jyz
jyz

Reputation: 6199

for blah in *.bx ; do mv ${blah} ${blah%%.bx}

Upvotes: 1

ghostdog74
ghostdog74

Reputation: 342303

Bash 4+

shopt -s globstar
shopt -s nullglob
shopt -s dotglob

for file in **/*.bx
do
  mv "$file" "${file%.bx}"
done

Upvotes: 2

Ken
Ken

Reputation: 78852

find -name "*.bx" -print0 | xargs -0 rename 's/\.bx//'

Upvotes: 2

Raghuram
Raghuram

Reputation: 52635

Assuming you are in the folder from where you want to do this

find . -name "*.bx" -print0 | xargs -0 rename .bx ""

Upvotes: 1

Related Questions