I have thousands of image files that have a 10-digit number appended to the beginning of the filenames. Immediately following each string of 10 numbers is an underscore. They look like this:


I need to remove the 10dig number and the underscore, without disturbing what follows, the result of which should look like this:


I'm using this command to find/replace other unwanted stuff in the filenames:

ls -1 | while read file; do new_file=$(echo $file | sed s/foo/bar/g); mv "$file" "$new_file"; done

How can I edit the above command to remove the leading 10dig+underscore combo(s) without altering the rest of the filename(s)?

migrated from serverfault.com Sep 24 '15 at 6:27

This question came from our site for system and network administrators.

  • 1
    Why not just use the standard rename command? – EEAA Sep 23 '15 at 18:25
  • @EEAA: rename is only standard in Linux. – cuonglm Sep 24 '15 at 6:34
  • @cuonglm Right, and the question is tagged with "linux". – EEAA Sep 24 '15 at 11:47
  • @EEAA: You should mention it explicitly, otherwise there's a chance that other persons can confuse. – cuonglm Sep 24 '15 at 11:57

Parsing ls output is considered bad practise by some. So it could look something like this (assuming posix shell):

for file in /path/to/file/*
    part_to_remove=$(echo "$file" | grep -Eo '[[:digit:]]{10}_')
    if ! [ -z $part_to_remove ]; then
        mv "$file" "new_file"


for f in ./*; do
  mv -- "$f" "${f#./[0-9]*_}"

Your Answer

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