0

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:

1318487644_IMG_2158.jpg

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

IMG_2158.jpg

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)?

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

2 Answers 2

0

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/*
do
    part_to_remove=$(echo "$file" | grep -Eo '[[:digit:]]{10}_')
    if ! [ -z $part_to_remove ]; then
        new_file="${file#$part_to_remove}"
        mv "$file" "new_file"
    fi 
done
0
0

POSIXly:

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

You must log in to answer this question.