【问题标题】:PowerShell rename filesPowerShell 重命名文件
【发布时间】:2021-02-03 20:00:27
【问题描述】:

我有一个充满 .pdf 和 .dwf 文件的数据库。 我需要重命名这些。

文件命名如下:

123456 text text.pdf

应该是这样的:

123456000_text_text.text.pdf

我可以用以下命令替换空格:

dir | rename-item -NewName {$_.name -replace " ","_"}

现在我需要一个命令,在前 6 位数字后插入 3 次“0”。

有人可以帮我吗?

已经谢谢了

【问题讨论】:

  • 到目前为止,您尝试过什么来添加零?数字总是 6 并且您想要一个 9 位数字吗?如果是12345,应该是12345000还是123450000?
  • 它总是 6,我需要 9
  • 我只是在思考或尝试是否可以像字符串一样拆分名称

标签: windows powershell


【解决方案1】:

您只需要过滤 *.pdf 和 *.dwf 文件,而且文件名是否符合以 6 位数字开头后跟空格字符的标准。然后你可以像这样使用正则表达式替换:

Get-ChildItem -Path D:\Test -File | Where-Object { $_.Name -match '^\d{6} .*\.(dwf|pdf)$' } | 
    Rename-Item -NewName { $_.Name -replace '^(\d{6}) ', '${1}000_' -replace '\s+', '_'}

之前:

D:\TEST
    123456 text text.dwf
    123456 text text.pdf
    123456 text text.txt

之后:

D:\TEST
    123456 text text.txt
    123456000_text_text.dwf
    123456000_text_text.pdf

文件名匹配的正则表达式详细信息:

^               Assert position at the beginning of the string
\d              Match a single digit 0..9
   {6}          Exactly 6 times
\               Match the character “ ” literally
.               Match any single character that is not a line break character
   *            Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
\.              Match the character “.” literally
(               Match the regular expression below and capture its match into backreference number 1
                Match either the regular expression below (attempting the next alternative only if this one fails)
      dwf       Match the characters “dwf” literally
   |            Or match regular expression number 2 below (the entire group fails if this one fails to match)
      pdf       Match the characters “pdf” literally
)              
$               Assert position at the end of the string (or before the line break at the end of the string, if any)

【讨论】:

  • 添加$_.FullName 而不仅仅是$_.Name
  • @AbrahamZinala 不,我正在传递 FileInfo 对象。
  • 你只是编辑它!?!大声笑可以发誓我没有看到它,我的错误(:
【解决方案2】:

你拥有的是123456 text text.pdf 希望它看起来像 123456000_text_text.pdf 实现这一目标的系统方法是>>

$const = "123456 text text.pdf"
$filename = $const -replace " ","_"
$temp = $filename.split("_")[0]
$rep1 = ([string]$temp).PadRight(9,'0')
$output =  $filename -replace $temp,$rep1 

Write-Host $output -ForegroundColor Green

这种方法的好处是它总是以 0 结尾,保持你的数字字符串为 9 位。

【讨论】:

    猜你喜欢
    • 2015-11-26
    • 1970-01-01
    • 2021-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多