How to keep a filename with only 20 characters and a file extension .txt

filenamesrename

I have a bunch of files like this:

hhsLog.8020.20200330}1585594173}0}coll_DefaultCollectorGroup_1_158594166_132642}1036942}0}0

I just want to keep the first 20 characters and add a .txt extension. So in the end I should have a file with the name:

hhsLog.8020.20200330.txt

I am working on both Fedora and Solaris.

Best Answer

You can easily do this with a shell loop in bash:

cd /path/to/files/;
for file in *; do
    echo mv -i -- "$file" "${file:0:20}.txt"
done

Once you are satisfied that does what you need, remove the echo to actually rename the files:

 cd /path/to/files/;
 for file in *; do
    mv -i -- "$file" "${file:0:20}.txt"
done

The -i will make mv ask before overwriting if one of the new names already exists.

Related Question