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 |3 Answers
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
- You may consider a backup at any time before you start a batch operation.
- 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. - You could also use
cut
、grep
、vim
orbash
, 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.
newfilename="${filename%%.*}.${filename##*.}"
? Or[[ $filename =~ ^(.*)\..*(\..*)$ ]] && newfilename="${BASH_REMATCH[1]}${BASH_REMATCH[2]}"
? – Renaud Pacalet Commented Mar 21 at 13:09.txt
. Is this a general rule? If so, you should say it in your question, because in this case, a trivial solution would benewname=${filename/.*/}.txt
. – user1934428 Commented Mar 21 at 14:05awk -F . '{print $1 "." $NF}'
? – pmf Commented Mar 21 at 15:16myfile.20240101.txt
->myfile..txt
? – Cyrus Commented Mar 21 at 16:03