[英]Capitalize all files in a directory using Bash
I have a directory called "Theme_1" and I want to capitalize all the filenames starting with "theme".我有一个名为“Theme_1”的目录,我想将所有以“theme”开头的文件名大写。 The first letter of every file name is lowercase and I want it to be upcase.
每个文件名的第一个字母都是小写的,我希望它是大写的。
I've tried this but all the letters in the filename are upcase, which is not what I want.我试过这个,但文件名中的所有字母都是大写的,这不是我想要的。
for f in * ; do mv -- "$f" "$(tr [:lower:] [:upper:] <<< "$f")" ; done
I also tried this, but it doesn't work:我也试过这个,但它不起作用:
mv theme*.jpg Theme*.jpg
In Bash 4 you can use parameter expansion directly to capitalize every letter in a word ( ^^
) or just the first letter ( ^
).在 Bash 4 中,您可以直接使用参数扩展来将单词中的每个字母 (
^^
) 或仅首字母 ( ^
) 大写。
for f in *; do
mv -- "$f" "${f^}"
done
You can use patterns to form more sophisticated case modifications.您可以使用模式来形成更复杂的案例修改。
But for your specific question, aren't you working too hard?但是对于你的具体问题,你是不是太努力了? Just replace the word "theme" with the word "Theme" when it occurs at the beginning of filenames.
当“主题”出现在文件名的开头时,只需将“主题”一词替换为“主题”。
for f in theme*; do
mv "$f" "Theme${f#theme}"
done
Your first attempt was close but tr
operates on every character in its input.您的第一次尝试很接近,但
tr
对其输入中的每个字符进行操作。
You either need to use something like sed
that can operate on a single character or limit tr
to only seeing the first character.您要么需要使用可以对单个字符进行操作的
sed
东西,要么将tr
限制为只能看到第一个字符。
for f in * ; do
mv -- "$f" "$(tr [:lower:] [:upper:] <<< "${f:0:1}")${f:1}"
done
That uses Shell Parameter Expansion to only give tr
the first character of the filename and then expand the rest of the filename after that.使用Shell Parameter Expansion仅给出
tr
文件名的第一个字符,然后扩展文件名的其余部分。
I couldn't get what I wanted in Bash.我无法在 Bash 中得到我想要的东西。 So I spent 2 minutes and got this working in PHP.
所以我花了 2 分钟,让它在 PHP 中工作。 This is for future googlers who are looking for a solution and happen to have PHP on their system.
这适用于正在寻找解决方案并且碰巧在他们的系统上安装 PHP 的未来 Google 员工。
<?php
foreach(glob(__DIR__.'/*') as $filename) {
if($filename === '.' || $filename === '..') { continue; }
// To only capitalize the first letter of the file
$new_filename = ucfirst(basename($filename));
// To capitalize each word in the filename
//$new_filename = ucwords(basename($filename));
echo __DIR__.'/'.$new_filename."\n";
rename($filename, __DIR__.'/'.$new_filename);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.