giordano
giordano

Reputation: 3152

Bash: How to replace a prefix of folders

I have a bunch of folders:

test_001
test_002

and I would like to replace the prefix test with ftp to get:

ftp_001
ftp_002

One problem: I have access on a Linux-Server with minimal installation. For example, rename is not installed and probably even sed is not installed. so, how can I replace the prefix using pure bash?

Upvotes: 1

Views: 560

Answers (2)

Kent
Kent

Reputation: 195049

This little script may help:

for dir in */
do
    mv "$dir" "${dir/test/ftp}"
done

execute it under the parent of your test_00x directory.

It could be written in a compact one-liner:

for dir in */; do mv "$dir" "${dir/test/ftp}"; done

Upvotes: 1

Allan
Allan

Reputation: 12438

Since you have a minimal installation I have tried to make a command that does not require tr, sed or find.

INPUT:

$ tree .
.
├── a
├── b
├── c
├── test_001
└── test_002

2 directories, 3 files

CMD:

for d in */; do mv "${d:0:-1}" "ftp"${d:4:-1}; done

OUTPUT:

tree .
.
├── a
├── b
├── c
├── ftp_001
└── ftp_002

2 directories, 3 files

Explanations about substrings in bash : https://www.tldp.org/LDP/abs/html/string-manipulation.html

Upvotes: 2

Related Questions