大网数据广告活动
服务器运维问答

Change first character pattern in a file name without changing that same pattern elsewhere in the file name

· 52CE 我爱测

On a Linux server I have a directory full of files with digits for names. Some of the files start with two zeros such as 00305005. I am writing a bash shell script and one of the steps is to rename all of the files that start wit…

问题原文

原帖链接 · DavevaD · CC BY-SA 4.0

On a Linux server I have a directory full of files with digits for names. Some of the files start with two zeros such as 00305005. I am writing a bash shell script and one of the steps is to rename all of the files that start with 00 so they start with @0. The file I mentioned earlier would be @0305005.

The issue I am having is that when I try to rename the files I end up changing all instances of 00 in the file name to @0 like this: @0305@05. I have been using the following code and I don't know how to fix it:

for f in 00*; do mv "$f" "${f//00/@0}"; done

已采纳解答

原帖链接 · Gordon Davisson · CC BY-SA 4.0

When you use ${var//pattern/replacement}, the // means "replace all occurrences". In this case you only want to replace the first occurrence, so you can use just /. Or, you could be even more specific, and use /#, which will replace only at the beginning of the string; this shouldn't make a difference since you're only processing files that start with 00, but I'd be inclined to use it to make the goal explicit. Here's a demo:

$ f=00305005
$ echo "${f//00/@0}"    # // = replace all
@0305@05
$ echo "${f/00/@0}"     # /  = replace first one -- this does what you want
@0305005
$ echo "${f/#00/@0}"    # /# = replace at beginning -- this also does what you want
@0305005
$ g=90305005            # Let's test with a name that *doesn't* start with 00
$ echo "${g/00/@0}"     # / replaces the first match, no matter where it is in the string
90305@05
$ echo "${g/#00/@0}"    # /# does not replace if the beginning does not match
90305005

I'd also recommend using mv -i for any sort of bulk move/rename, to avoid data loss if there's a naming conflict or error. Thus, here's what I'd recommend:

for f in 00*; do mv -i "$f" "${f/#00/@0}"; done

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2019-07-12)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 4.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。