问题描述
在当前目录中:文件夹:001、002、003、004 ......等我想将后缀'_ses-1'添加到所有文件夹中,例如001_ses-1
尝试
for d in *; do mv "$d" "${d}_ses-1"; done
find ./ -type d -exec bash -c mv "$folder" "${folder}_ses-1"
所有操作都失败了,希望对此有所帮助。
解决方法
第一个命令(for
)仅与目录不匹配。
如果目录目录嵌套,则第二个(find
)有问题。
如果没有嵌套文件夹,则可以使用:
find . -maxdepth 1 -type d -exec mv {} {}_ext \;
,
假设这是一项一次性的任务,并且不需要递归,一个技巧是将ls
的输出传递到文本文件中,运行一个宏(例如,在vim中)以对其进行转换是正确的mv
命令,然后将整个程序作为脚本运行。
另一种选择是使用bash作为单独的mv
命令来生成每个命令(类似于您已经尝试过的命令),并通过管道将其作为脚本运行。
我喜欢find ./
方法,但是它可能会发现.
和..
然后无法移动它们。
find ./ -type d ! -name . ! -name .. -exec bash -c mv "$folder" "${folder}_ses-1"
对于for d in *;
方法,您需要这样做以遍历列表:
for d in `ls -1`; do mv "$d" "${d}_ses-1"; done
,
使用rename
命令,其用法如下:find ... | xargs rename ...
。 rename
命令具有多种实现,并且功能非常强大。与简单的mv
相比,它可以用于更复杂的操作。
示例:
# Create a tiny test with 4 input directories:
$ mkdir 001 002 003 004
$ ls -d 00[1-4]*
001 002 003 004
# Do a dry run first using -n option:
$ find . -type d -name '00[1-4]' | xargs rename -n 's/$/_ses-1/'
'./001' would be renamed to './001_ses-1'
'./003' would be renamed to './003_ses-1'
'./004' would be renamed to './004_ses-1'
'./002' would be renamed to './002_ses-1'
# Actually rename for real:
$ find . -type d -name '00[1-4]' | xargs rename 's/$/_ses-1/'
# Confirm the results:
$ ls -d 00[1-4]*
001_ses-1 002_ses-1 003_ses-1 004_ses-1
请注意,rename
可以轻松安装,例如使用conda
:
conda install rename
另请参见:
rename
手册(非常有帮助):
rename --man
例如:
-n,--dry-run,--just-print
Show how the files would be renamed,but don't actually do anything.