Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
560 views
in Technique[技术] by (71.8m points)

linux - Rename files in multiple directories to the name of the directory

I have something like this:

v_1/file.txt
v_2/file.txt
v_3/file.txt
...

and I want to rename those files to something like this:

v_1.txt
v_2.txt
v_3.txt
...

in the same directory.

I guess I can use rename but I can't figure out how to use it with folder and file renaming at the same time.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The result can be achieved with a bash for loop and mv:

for subdir in *; do mv $subdir/file.txt $subdir.txt; done;

Note that the solution above will not work if the directory name contains spaces. Related link.

Another solution based on comments (that works for directories having spaces in the name as well):

find . -type d -not -empty -exec echo mv {}/file.txt {}.txt ;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...