最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Removing the extra file extension in bash - Stack Overflow

programmeradmin9浏览0评论
filename='myfile.20240101.txt'
filename2='otherfile.20240303.txt'
filename3='anotherfile.2025.txt'

I want to remove the middle part between the dots. I will take a look at awk, but is there an 'easier' way?

base.numbers.txt

filename='myfile.20240101.txt'
filename2='otherfile.20240303.txt'
filename3='anotherfile.2025.txt'

I want to remove the middle part between the dots. I will take a look at awk, but is there an 'easier' way?

base.numbers.txt

Share Improve this question asked Mar 21 at 13:02 PaulMPaulM 3852 silver badges13 bronze badges 4
  • 6 newfilename="${filename%%.*}.${filename##*.}"? Or [[ $filename =~ ^(.*)\..*(\..*)$ ]] && newfilename="${BASH_REMATCH[1]}${BASH_REMATCH[2]}"? – Renaud Pacalet Commented Mar 21 at 13:09
  • 1 In all your examples, the filenames end in .txt. Is this a general rule? If so, you should say it in your question, because in this case, a trivial solution would be newname=${filename/.*/}.txt. – user1934428 Commented Mar 21 at 14:05
  • Re "I will take a look at awk": How about awk -F . '{print $1 "." $NF}'? – pmf Commented Mar 21 at 15:16
  • myfile.20240101.txt -> myfile..txt? – Cyrus Commented Mar 21 at 16:03
Add a comment  | 

3 Answers 3

Reset to default 4
$ filename='myfile.20240101.txt'
$ [[ "$filename" =~ (.*)\..*(\..*) ]] && echo "${BASH_REMATCH[1]}${BASH_REMATCH[2]}"
myfile.txt

Perl file-rename

# Preview changes first (dry-run)
rename -n 's/\.\d+\.txt$/.txt/' *.txt

# Execute renaming
rename 's/\.\d+\.txt$/.txt/' *.txt
  • Breakdown: \.\d+\.txt$ Matches . followed by digits \d+ before the final .txt

Alternative Pattern non-numeric suffixes

rename 's/\..*\.txt$/.txt/' *.txt  # Removes everything between first and last dot

Notes

  1. You may consider a backup at any time before you start a batch operation.
  2. Use type rename ; whatis !$ ; apt info !$ to check the rename command, which should be installed by default in common distributions
    man perl to learn more, also see the pcre namespace manual.
  3. You could also use cutgrepvim or bash , but they're not the easier.
#!/bin/bash

directory=${1:-.}

for file in "$directory"/*.*.*; do
    new_name="$(echo "$file" | sed -E 's/(^[^.]+)\..*\.(.*$)/\1.\2/')"
    cp "$file" "$new_name"
done

If you copy this script to a file and give it executable permission you should get your intended result. You might want to change the directory name.

It works by giving sed the name of the file as an input. Sed then removes the numbers which come between two dots

Then cp creates a copy of the renamed file.

发布评论

评论列表(0)

  1. 暂无评论