1

I had 1000 directories with different names, but the files in all those directories has a files starting with tran-20.ft, tran-30.ft, tran-40.ft, tran-50.ft, tran-60.ft.

Directory structure

dir1 ---tran-20.ft
  :     tran-30.ft
  :     tran-40.ft
  :     tran-50.ft
  :     tran-60.ft
  :
dir1000

Expected output

dir1 --- dir1_tran-20.ft
         dir1_tran-30.ft
         dir1_tran-40.ft
         dir1_tran-50.ft
         dir1_tran-60.ft

I'd like to add directory name as a prefix to specific files(tran*) only? How I do that?

Chris Davies
  • 116,213
  • 16
  • 160
  • 287

1 Answers1

4

Like this with parameter expansions:

for f in */tran-*.ft; do
    echo mv "$f" "${f%%/*}/${f%%/*}_${f##*/}"
done

Remove the echo when outputs looks good enough


Or like this with Perl's rename:

rename -n 's!^([^/]+)/(tran-\d+\.ft)!$1/${1}_$2!' */tran-*.ft

Remove the -n switch when outputs looks good enough

  • I tried it's not working. But it shows in echo ? result file remains same, no prefix added to files. – sunnykevin Jun 14 '20 at 16:19
  • 2
    Did you read what I wrote ? Remove the echo when outputs looks good enough – Gilles Quénot Jun 14 '20 at 16:26
  • Sorry @ Gilles I confused my self, It working. Thanks! – sunnykevin Jun 14 '20 at 17:37
  • What exactly do you mean by pure shell? The second command looks purer shell style as it does one invocation of the appropriate command for the task while the first one runs many invocations of mv in a loop. – Stéphane Chazelas Jun 14 '20 at 19:35
  • 1
    Maybe 'simple' would be more appropriate than 'pure'. Anyway, removed this mention. I know rename is better, but many times I show this, the OP don't understand or don't want to install 'external tools' and prefer what he whows better, like my first snippet. That's why I show both methods – Gilles Quénot Jun 14 '20 at 19:36