0

I am using Ubuntu and I have lots of files. The files have two types.

"img_00000_c0_1283347740957299us.jpg" 
"img_00000_c1_1283347740342342us.jpg"

They are distinguished by c0 or c1. The numbers in the position '00000' increase as the file number goes up. For example, type c0 and 5th file would have name "img_00005_c0_1283347740957299us.jpg". The problem is, the long numbers after 'c0_' or 'c1_' is meaningless to me and they are random numbers. They are not always '1283347740957299us'. Therefore I want to rename those files just eliminating those last numbers.

img_00005_c1_1283347740957299us.jpg ---> img_00005_c1.jpg

I tried several answers in the Internet. For example, an answer like

for FILE in eventDataLog.txt.2015*; do mv "$FILE" "abc-$FILE"; done

I guess the code above from this answer would help me, but for my case, the renaming is not adding characters. I also found some answers about subtracting parts of the name in here, but my case has random numbers.

Thanks in advance!

2 Answers2

2

A couple of options, both simply removing the shortest _ suffix from the end of the name:

  1. with the perl-based prename command

    $ prename -nv -- 's/_[^_]*\.jpg/.jpg/' *.jpg
    img_00000_c0_1283347740957299us.jpg renamed as img_00000_c0.jpg
    img_00000_c1_1283347740342342us.jpg renamed as img_00000_c1.jpg
    

(remove the n option when you're happy with the output)

  1. using shell parameter expansion

    $ for f in img_*.jpg; do echo mv -- "$f" "${f%_*}.jpg"; done
    mv -- img_00000_c0_1283347740957299us.jpg img_00000_c0.jpg
    mv -- img_00000_c1_1283347740342342us.jpg img_00000_c1.jpg
    

(remove the echo when you're happy with the output).

If you want to match the pattern more specifically (i.e. as a sequence of one or more decimal digits, followed by us) then you can do so, but it doesn't seem to be necessary based on the information you have given.

steeldriver
  • 81,074
0

It seems there are 16 digits just before the string us. You can use rename to remove those 18 characters in total, as shown below.

rename -v 's/_(\d){16}us//' *.jpg
img_00000_c0_1283347740957299us.jpg renamed as img_00000_c0.jpg
img_00000_c1_1283347740342342us.jpg renamed as img_00000_c1.jpg
img_00005_c1_1283347740957299us.jpg renamed as img_00005_c1.jpg

The -v (verbose) option shows the file names that are renamed. The (\d){16} pattern indicates a group of 16 digits. The output shown above is based on three sample input files. You can also look at more examples on rename.

Barun
  • 2,376