-1

Is there a quick and clever way to remove various timestamps from multiple files with different names? The timestamp format always remains the same, although the values differ. An example of my files would be...

A_BB_CC_20180424_134312
A_B_20180424_002243
AA_CC_DD_E_20180424_223422
C_DD_W_E_D_20180423_000001

with the expected output

A_BB_CC
A_B
AA_CC_DD_E
C_DD_W_E_D

Notice the last file has a different timestamp, I don't mind if this is a day specific timestamp removal or all, or two variations. My problem is I can't think of the code for an ever changing time value :(

Thanks in advance

EDIT - Adding edit in to show why this is not a duplicate as Tripleee thinks. His duplicate link is for files with the same prefix, my question is about files with different names so the answer is different.

Richard C
  • 401
  • 1
  • 5
  • 19
  • @tripleee - Not a duplicate as the question you have highlighted is for when all the files have the same prefix. My question has different filenames for each file, so its a different answer! – Richard C May 08 '18 at 12:10
  • I have redirected to a different duplicate, thanks for the ping. – tripleee May 08 '18 at 12:15

2 Answers2

1

Using parameter expansion %% bashism that removes the end of the filename:

for i in /my/path/*; do mv  "$i" "${i%%_2018*}"; done

This relies on the timestamp that start with 2018...


Using awk:

for i in /my/path/*; do mv "$i" $(awk -v FS=_ 'NF-=2' OFS="_" <<< "$i"); done

This awk script is based on the field separator _. It prints the filename without the last 2 field representing the timestamp.

oliv
  • 12,690
  • 25
  • 45
1

In order to rename a set of files and apply regular expressions in the renaming process you can use the rename command.
So in your example:

rename 's#_[0-9]*_[0-9]*##' *_[0-9]*

This renames all files in the current directory ending with _ followed by digits.
It cuts away all _ followed by digits followed by _ followed by digits.

pitseeker
  • 2,535
  • 1
  • 27
  • 33