I want to rename files by removing the last N characters
For example I want to rename these files by removing the last 7 characters
From:
file.txt.123456
To:
file.txt
Is this doable in a single command?
You can remove a fixed number of characters using
mv "$file" "${file%???????}" # 7 question marks to match 7 characters
This will work in any POSIX-compliant shell.
To remove the last extension (which may be more or less than 7 characters), use
mv "$file" "${file%.*}"
To trim everything after a given extension, you can try
EXT=csv
mv "$file" "${file%.$EXT.*}".$EXT
which actually removes .$EXT
and everything after, but then reattaches .$EXT
.
Are you using bash?
file="file.txt.123456"
mv $file ${file::(-7)}
This is similar to Adam's, but without bashisms (since it was tagged shell not bash).
remove_n(){
echo ${2:0:$((${#2}-$1))}
}
remove_n 8 file.txt.1234567
#remove last 8 characters from 2nd argument
#for filenames in variables use
mv "$VAR" `remove_n 8 "$VAR"`
To do so for every file in directory you can use this.
As in first answer 7 question marks to match 7 characters
for file in *; do mv "$file" "${file%???????}"; done
Depending on what you mean by a single command, at least you can do it with some pipes:
mv file.txt.123456 $(ls file.txt.123456 | rev | cut -c8- | rev)
Looking at your example, I'm wondering if a pattern like "removing characters from the last dot to the end" would be a better fit.