-2

Write the command that will locate all files that have the suffix/extension of .py. For each file that is located, the command should append the suffix/extension of .backup to the file. So, if a file had the name one.py, its new name would be one.py.backup.

I tried

find . / -name "*.py" -type f -exec mv {} {}.backup \;

and it did not work

3
  • 1
    You have a small typo, probably you mean find . -type f -name "*.py" -exec mv {} {}.backup \; and if it doesn't work, please update the question with the exact error/reason.
    – thanasisp
    Commented Nov 12, 2020 at 19:21
  • 1
    it worked. thanks Commented Nov 12, 2020 at 21:29
  • Where are the files located? Only in the current directory, or also in sub-directories?
    – AdminBee
    Commented Nov 13, 2020 at 12:39

2 Answers 2

1

A shell-based solution could also work, since the task here is easy enough (simply appending a string fragment to a filename)

for file in *.py; do newname="$file.backup"; mv "$file" "$newname"; done

If it is possible that no such file exists, you would need to catch that case explicitly. Assuming bash, you could use the nullglob option:

shopt -s nullglob; for file in *.py; do newname="$file.backup"; mv "$file" "$newname"; done

or test explicitly if the file exists:

for file in *.py; do newname="$file.backup"; [ -f "$file" ] && mv "$file" "$newname"; done

If the files in question can also be in sub-directories, things get more complicated. With bash v4 onwards, you can use the globstar option:

shopt -s globstar; for file in **/*.py; do newname="$file.backup"; mv "$file" "$newname"; done

Again, you may have to combine with shopt -s nullglob to account for the case no such file exists.

0

I believe you can start doing something like:

> find PATH -name "*.py"

where you can change the PATH to the desired folder you want to look for... and them you could pipe the output with another command like mv using xargs.

2
  • Thank you for your contribution. Please note, however, that complete answers are preferred; you may want to expand your proposed solution with one of the methods you mention to make a full example out of your post.
    – AdminBee
    Commented Nov 13, 2020 at 12:50
  • @AdminBee ok... sorry for the incomplete answer. Commented Nov 18, 2020 at 19:26

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .