I have some files in /home/Desktop/Code directory. How can I change the file name which is last modified to a name "test.cpp" using terminal.

  • You can change file names using the mv command. Run man mv for more info about it.
    – Wayne_Yux
    Oct 28, 2015 at 10:11
  • Also with the -toption of lscommand you can sort the files by modification date
    – migrc
    Oct 28, 2015 at 10:23

1 Answer 1


Try this: ls -t | head -n 1 | xargs -I '{}' mv '{}' test.cpp


ls -t sort the files by last modification date

head -n 1 selects the first name that previous command returned (last modified file)

xargs -I '{}' mv '{}' test.cpp this command execute the mv command replacing the '{}' with string received from standard input (in this case through the pipe) (The command would be mv last_modified_file test.cpp)

To avoid directories:

ls -t `find -maxdepth 1 -type f` | head -n 1 | xargs -I '{}' mv '{}' test.cpp


  • Can you give a solutions which avoids last modified folders and only works for files. Your solution seems harmful.
    – froghramar
    Oct 28, 2015 at 17:17
  • I've updated my answer.
    – migrc
    Oct 28, 2015 at 17:57
  • 1
    +1 since this is good in most cases, but mind also that it would break on filenames containing newlines
    – kos
    Oct 28, 2015 at 18:42
  • Yes, it's possible.
    – migrc
    Oct 28, 2015 at 18:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.