开发者

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

开发者 https://www.devze.com 2023-01-18 03:21 出处:网络
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 \".\" prefi

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, 开发者_如何学JAVAsome 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!


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


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


Bash 4+

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

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


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

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


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


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消