0

I have files in a directory such as

FILE1.docx.txt
FILE2.docx.txt
FILE3.docx.txt
FILE4.docx.txt
FILE5.docx.txt

And I would like to remove .docx from all of them to make the final output such as

FILE1.txt
FILE2.txt
FILE3.txt
FILE4.txt
FILE5.txt

How do I do this?

3 Answers 3

3

With Parameter Expansion and mv

for f in *.docx.txt; do
  echo mv -vn "$f" "${f%%.*}.${f##*.}"
done

The one-liner

for f in *.docx.txt; do echo mv -vn "$f" "${f%%.*}.${f##*.}"; done        

Remove the echo if you think the output is correct, to rename the files.

Should work in any POSIX compliant shell, without any script.


With bash, enable the nullglob shell option so the glob *.docx.txt will not expand as literal *.docx.txt if there are no files ending with .docx.txt

#!/usr/bin/env bash

shopt -s nullglob

for f in *.docx.txt; do
  echo mv -vn "$f" "${f%%.*}.${f##*.}"
done

UPDATE: Thanks to @Léa Gris add nullglob change the glob to *.docx.txt and add -n to mv, Although -n and -v is not defined by POSIX as per https://pubs.opengroup.org/onlinepubs/9699919799/utilities/mv.html It should be in both GNU and BSD mv

Sign up to request clarification or add additional context in comments.

1 Comment

Don't forget shopt -s nullglob in case no file match the *.txt globbing pattern. Also you can restrict the globbing pattern to candidates only with for f in *.docx.txt, Prefer mv -n to not overwrite existing files.
1

Just run this python script in the same folder that contains files:

import os

for file in os.listdir(os.getcwd()):
    aux = file.split('.')
    if len(aux) == 3:
        os.rename(file, aux[0] + '.' + aux[2])

Comments

0

you can make use of sed and bash like this:

for i in *.docx.txt
do
    mv "$i" "`echo $i | sed 's/.docx//'`"
done

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.