0

I am trying to rename a bunch of files according to the names of their directory in Linux, SSH.

I have a directory called XYZ01smith. In it are four files called smith_5*.I need to add prefix XYZ01 to these files.
But, the next directory is called XYZ02perry. In it are four files called perry_3*. I need to add the prefix XYZ02 to these files.

I have a loop to do this per directory:

for i in smith_5*;
    do mv ${i} XYZ01${i};
done 

But I have 50 directories (XYZ01name to XYZ50name), so I would rather be able to do this with one script for all 50. I am sure this should be possible, but I do not know how.

2

With zsh:

autoload zmv # best in ~/.zshrc
zmv '(XYZ??)(*)/(*)' '$1$2/$1$3'
| improve this answer | |
  • Thank you, but is there a way to do this with ssh? – SSK Aug 28 '15 at 10:38
2

With bash:

for f in XYZ*/*; do mv -v "$f" "${f%/*}/${f:0:5}${f##*/}"; done

The for loop runs trough all XYZ* directories. Then the mv command renames the files.

Where:

  • $f is the original filename
  • ${f%/*} is the directory name
  • ${f:0:5} is the prefix
  • ${f##*/} is the original filename
| improve this answer | |
0

You can run this command which just shows you what it would do:

ls -d XYZ*/* |
sed -n s'|\(XYZ[0-9][0-9]\)\([^/]*\)/\(\2_.*\)|mv & \1\2/\1\3|p' |
cat

and if you like the commands to run, replace cat by sh.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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