I have more than hundred directories named SP_[number]_date. I'd like to rename all to just SP_[number].

I can only figure out how to do that by mv SP_1_date SP_1 but that will take ages. Can I rename all at once? I thought that I could do something like for num in ./*; do mv SP_$num_date SP_$num; done but it doesn't do the trick.

  • 1
    The rename expression would be s/_date$// – muru Aug 10 '15 at 7:20
  • is date literal or is a date, like in SP_1_May 12, 2015? – Rmano Aug 10 '15 at 10:50
  • The reason mv SP_$num_date SP_$num didn't work was that you don't have a variable $num_date (or, at least, that's one of the reasons). You would have needed ${num}_date to separate the variable $num from a constant suffix _date. Another problem is that the value in $num might be ./SP_1_date so the mv command was attempting to move SP_./ (since $num_date was undefined and hence an empty string) to SP_./SP_1_date. – Jonathan Leffler Aug 10 '15 at 14:30

A simple enough bash way:

for i in *_date
    mv "$i" "${i%%_date}"

${i%%_date} removes a trailing _date from the string in i.

  • That would be great! So how many % should I add, when the number is up to four digits eg. SP_2200_date? – Ditte Aug 10 '15 at 7:26
  • @Ditte oh, the % is not related to the number of digits. %% removes the longest matching suffix , % removes the shortest matching suffix. For example, if I did ${i%_*date}, I'd get SP_2200, and if I did ${i%%_*date}, I'd get SP. In the case of the answer, it makes no difference, as I'm not using any wildcard. – muru Aug 10 '15 at 7:29
  • @Ditte search for %% in tldp.org/LDP/abs/html/string-manipulation.html – muru Aug 10 '15 at 7:30
  • I accidently only wrote one % and now they're all SP_num_date%_date... :( I can't really understand why I just can't use mv SP_$num_* SP_$num. Should I change switch the order of the "$i" and "$i%%_date-date" then? – Ditte Aug 10 '15 at 7:45
  • 1
    @Ditte It's ${i%%_date}! With the braces! – muru Aug 10 '15 at 8:29

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