Linux的shell脚本添加前导零到文件名 [英] linux shell script to add leading zeros to file names

查看:610
本文介绍了Linux的shell脚本添加前导零到文件名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个约1700文件的文件夹。他们都是这样命名的1.txt 1497.txt 等。我想重新命名所有的文件,使所有的文件名是4位数字。

I have a folder with about 1700 files. They are all named like 1.txt or 1497.txt etc. I would like to rename all the files so that all the filenames are 4 digits long.

IE 23.txt 变成 0023.txt

什么是一个shell脚本,将做到这一点?或一个相关的问题:我如何使用grep到包含 \\ d.txt (即1位,那么一个时期,那么唯一的字母匹配线 TXT )?

What is a shell script that will do this? Or a related question: How do I use grep to only match lines that contain \d.txt (IE 1 digit, then a period, then the letters txt)?

下面是我到目前为止有:

Here's what I have so far:

for a in [command i need help with]
do
  mv $a 000$a
done

基本上,运行3次,用命令那里找到1位,2位和3位数字的文件名(初始零的个数变化)

Basically, run that 3 times, with commands there to find 1 digit, 2 digit, and 3 digit filenames (with the number of initial zeros changed)

推荐答案

尝试:

for a in [0-9]*.txt; do
    mv $a `printf %04d.%s ${a%.*} ${a##*.}`
done

更改文件名模式( [0-9] *。TXT )是必要的。

Change the filename pattern ([0-9]*.txt) as necessary.

一个通用的枚举重命名,使得没有关于初始设置文件名的假设:

A general-purpose enumerated rename that makes no assumptions about the initial set of filenames:

X=1;
for i in *.txt; do
  mv $i $(printf %04d.%s ${X%.*} ${i##*.})
  let X="$X+1"
done


在同一主题:

  • Bash script to pad file names
  • Extract filename and extension in bash

这篇关于Linux的shell脚本添加前导零到文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆