使用 Powershell 从文件重命名范围 - 从最后一个连字符的第一个到第三个 [英] Renaming a range from files w/Powershell - from first to third from last hyphen

查看:42
本文介绍了使用 Powershell 从文件重命名范围 - 从最后一个连字符的第一个到第三个的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一堆 csv 文件,我想用 powershell 重命名.

I have a bunch of csv files I would like to rename with powershell.

来自

abc-def-ghi-jkl-mno-pqr-ke-traffic-by-domains-17-Oct-2018_23-49-38-6d73395f476ad09a7506dc00533933b8.csv
abc-def-ghi-jkl-mno-pqr-ke-traffic-by-domains-15-Oct-2018_05-20-36-75eabae7c4123198ff5fe6f4f642449f.csv
abc-def-ghi-jkl-mno-pqr-ke-traffic-by-domains-12-Oct-2018_06-23-58-b13eb8f362c09fbe405458fac8af8f8e.csv

abc-17-Oct-2018.csv
abc-15-Oct-2018.csv
abc-12-Oct-2018.csv

我可以用这个命令删除下划线 (_) 后面的字符

I could delete the characters after the underscore (_) with this command

Get-ChildItem -Filter *.csv | Foreach-Object -Process { 
    $NewName = [Regex]::Match($_.Name,"^[^_]*").Value + '.csv'
    $_ | Rename-Item -NewName $NewName}

这让我找到了这个文件名

which leads me to this file name

abc-def-ghi-jkl-mno-pqr-ke-traffic-by-domains-17-Oct-2018.csv

但是我无法删除从第一个连字符到最后一个连字符的第三个字符范围.

but I am lost at deleting the range of characters from the first hyphen to the third from last hyphen.

我试过了,但出现错误.

I tried this but get an error.

Get-ChildItem -Filter *.csv | Rename-Item -NewName { 
-replace '^[^-]..^[^-]{-3}','^[^-]'}

有人可以请教我如何擦除范围吗?(并可能结合前一个命令)

Could somebody kindly enlighten me how to erase a range? (and possibly combine the former command)

推荐答案

假设所有输入文件名在相同位置具有相同数量的标记和相同的分隔符:

Assuming that all input filenames have the same number of tokens with the same separators in the same positions:

Get-ChildItem -Filter *.csv | Rename-Item -NewName { 
  (($_.Name -split '[-_]')[0, 10, 11, 12] -join '-') + '.csv' 
} -WhatIf

-WhatIf 预览 重命名操作;删除它以执行实际重命名.

-WhatIf previews the renaming operations; remove it to perform actual renaming.

通过分隔符将文件名拆分为标记避免了复杂的正则表达式;PowerShell 灵活的数组切片功能可以轻松地将目标文件名与通过其索引访问的感兴趣的标记拼凑在一起.

Splitting the filename into tokens by separators avoids complex regexes; PowerShell's flexible array slicing makes it easy to piece together the target filename from the tokens of interest accessed by their indices.

也就是说,如果你想用 -replace 和一个复杂的正则表达式来实现:

That said, if you wanted to do it with -replace and a complex regex:

Get-ChildItem -Filter *.csv | Rename-Item -NewName { 
  $_.Name -replace '^([^-]+).*?-(\d[^_]+).*', '$1-$2.csv' 
} -Whatif

此解决方案不假设要提取的第二个标记的固定位置 - _ 之前的那个 - 而是通过 - 后跟一个数字来标识其开始(\d).

This solution doesn't assume a fixed position of the 2nd token to extract - the one before _ - and instead identifies its start by a - followed by a digit (\d).

这篇关于使用 Powershell 从文件重命名范围 - 从最后一个连字符的第一个到第三个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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