AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • 主页
  • 系统&网络
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • 主页
  • 系统&网络
    • 最新
    • 热门
    • 标签
  • Ubuntu
    • 最新
    • 热门
    • 标签
  • Unix
    • 最新
    • 标签
  • DBA
    • 最新
    • 标签
  • Computer
    • 最新
    • 标签
  • Coding
    • 最新
    • 标签
主页 / computer / 问题 / 1533871
Accepted
Remus Rigo
Remus Rigo
Asked: 2020-03-20 01:18:35 +0800 CST2020-03-20 01:18:35 +0800 CST 2020-03-20 01:18:35 +0800 CST

如何重命名文件 - 删除名称并保留编号

  • 772

我需要重命名许多包含名称和徽章编号的文件。

文件如下所示:“John Doe 1234.txt”,我必须将其重命名为 1234.txt
(新文件必须仅包含徽章编号)。
徽章编号也不是固定的,它可以包含 3-4 个数字。

更新:文件名包含 2-3 个用空格分隔的名称。例如:“John Doe 123.txt”或“John Junior Doe 1234.txt”

我想删除名称中的所有字母和空格,只保留数字,但我不知道 Powershell 足够好。

谁能帮我吗?

powershell batch-file
  • 6 6 个回答
  • 459 Views

6 个回答

  • Voted
  1. Narzard
    2020-03-20T01:36:54+08:002020-03-20T01:36:54+08:00

    假设所有文件名的格式为“First Last Number.txt

    你可以运行:

    pushd "C:\Temp\su\"
    dir | ? { $_.Name -like "*.txt" } | 
    % { Rename-Item $_ "$($_.BaseName.split(' ')[2])$($_.Extension)" }
    popd
    

    更改第一行以匹配您的路径。(粘贴整个片段并按两次回车键)

    显示开始文件名、命令和结果的屏幕截图。

    • 2
  2. Best Answer
    HaxAddict1337
    2020-03-22T00:18:48+08:002020-03-22T00:18:48+08:00

    文件名不能包含特殊字符(/\:*?"<>|),但可以包含诸如%和之类的字符,!这会导致cmd.exe误解,因此代码不是万无一失的。 代码现在是万无一失的。

    @echo off
    SETLOCAL ENABLEDELAYEDEXPANSION
    
    set "dir=YOUR DIRECTORY HERE"
    set "_output="
    set "map=0123456789"
    
    pushd "%dir%"
    
    FOR %%a in (*.txt) do (
        SETLOCAL
        set "file=%%~na"
        1>temp.log echo(!file!
        for %%b in (temp.log) do set /A len=%%~zb-2
        del /F /Q temp.log
        for /L %%A in (0 1 !len!) do (
            for /F "delims=*~ eol=*" %%? in ("!file:~%%A,1!") do if "!map:%%?=!" NEQ "!map!" set "_output=!_output!%%?"
        )
        ren "!file!.txt" "!_output!.txt"
        ENDLOCAL
    )
    ENDLOCAL
    

    截屏:


    注意:最多只能处理 31 个文件,因为SETLOCAL 我的假设是错误的。它可以处理无限的文件,因为配对SETLOCAL和ENDLOCAL.

    • 1
  3. Keith Miller
    2020-03-20T08:49:09+08:002020-03-20T08:49:09+08:00

    电源外壳:

    根据需要编辑$Source。“ -WhatIf ”参数意味着可以运行发布的代码来验证是否找到了所需的文件并且 NewName 是正确的。删除“ -WhatIf ”参数以实际重命名文件。

    $Source = 'c:\path\to\files'
    Get-CHildItem $SOurce *.txt -File |
        Rename-Item -NewName { $_.Name.Split(' ')[-1] } -whatIf
    
    • 0
  4. Lee_Dailey
    2020-03-20T12:17:41+08:002020-03-20T12:17:41+08:00

    假设所有输入文件都以空格结尾,然后至少有一个数字,这看起来像是另一种完成这项工作的方法。它不检查重复号码。[咧嘴笑]

    它能做什么 ...

    • 定义源和目标目录
      我总是对破坏原始文件感到不安,所以这会复制它们而不是重命名它们。如果您想直接执行此操作,请将 替换Copy-Item为Rename-Item。

    • 当您准备好实际操作时, 创建一些测试目录和文件会删除整个区域。
    • 定义要抓取的文件类型
    • 获取与过滤器匹配的文件
    • 删除所有.BaseNameprops 不以空格和至少一位数字结尾的 文件
    • 拆分.Basename空格并抓取结果中的最后一项
    • 将.Extension道具添加到上面
    • 构建新的完整文件名
    • 将 OLD 完整文件名复制到 NEW 完整文件名
    • -PassThru在线将Copy-Item“创建文件”信息发送到屏幕

    编码 ...

    $SourceDir = "$env:TEMP\InFiles"
    $DestDir = "$env:TEMP\OutFiles"
    
    #region >>> make some test dirs & files
    $SourceDir, $DestDir |
        ForEach-Object {
            $Null = mkdir -Path $_ -ErrorAction 'SilentlyContinue'
            }
    # the last file is not to be worked on - wrong pattern
    @'
    FName LName 1234.txt
    Alfa Bravo Charlie 89.txt
    First Middle Last 666.txt
    Wiki Tiki Exotica Music.txt
    '@ -split [System.Environment]::NewLine |
        ForEach-Object {
            $Null = New-Item -Path $SourceDir -Name $_ -ItemType 'File' -ErrorAction 'SilentlyContinue'
            }
    #endregion >>> make some test files
    
    $Filter = '*.txt'
    Get-ChildItem -LiteralPath $SourceDir -Filter $Filter -File |
        Where-Object {
            # filter out any basename that does NOT end with a space followed by at least one digit
            $_.BaseName -match ' \d{1,}$'
            } |
        ForEach-Object {
            # split on the spaces & take the last item from the resulting array
            $NewBaseName = $_.BaseName.Split(' ')[-1]
            $NewFileName = '{0}{1}' -f $NewBaseName, $_.Extension
            $FullNewFileName = Join-Path -Path $DestDir -ChildPath $NewFileName
            Copy-Item -LiteralPath $_.FullName -Destination $FullNewFileName -PassThru
            }
    
    • 0
  5. Durry42
    2020-03-23T18:07:50+08:002020-03-23T18:07:50+08:00

    您可以使用以下方法对批处理文件执行此操作。

    无论开头有多少个字母和空格,这都会起作用。

    @echo off
    setlocal enabledelayedexpansion
    
    set "fPath=C:\test\my files\"
    
    :: For each .txt file found in path %fPath% do....
    for /F "tokens=*" %%a in ('DIR /B /ON "%fPath%*.txt"') do (
        echo Processing: %%a
        set "oName=%%a"
        set "fName=%%a"
        call :loop
    )
    echo Finished
    endlocal
    pause
    
    :eof
    exit /B
    
    
    
    ::=====================================================================
    :: Check if the name is only numbers plus ".txt" on the end and if not, then remove the first character and check again.
    :: If only numbers remaining, rename the original file. If no characters left then no match found and should go to next file.
    
    :loop
    if "!fName!"==".txt" exit /B
    echo !fName!|findstr /r /c:"^[0-9]*\.txt$">nul
    if !errorlevel! NEQ 0 set "fName=!fName:~1!" && goto :loop
    ren "%fPath%%oName%" !fName!
    exit /B
    
    • 0
  6. Io-oI
    2020-04-02T15:30:23+08:002020-04-02T15:30:23+08:00

    您无需创建额外的 temp.log 文件来执行此任务,也无需担心文件名中的非数字字符...

    如果您U N I C O D E要这样做,请在循环中进行过滤for,并且仅从文件名中获取数字输出,可以通过以下方式完成:

    cmd /u "echo\ string" | findstr regex

    1)cmd /u将echo\string逐个字符命名

    cmd /u /c echo\John Doe 123.txt

    2)将在循环中仅findstr [0-9]获得变量编号!_n!%%~n

    echo\John Doe 123.txt|%__APPDIR__%findstr.exe [0-9]

    3)使用变量通过仅连接输出数字!_n!来增加%%~n字符

    set "_n=!_n!%%~n"
    @echo off && setlocal EnableDelayedExpansion
    
    pushd "c:\path\to\your\files"
    set "_where=%__APPDIR__%where.exe" 
    set "_findstr=%__APPDIR__%findstr.exe [0-9]"
    
    for /f "tokens=*" %%S in ('!_where! .:"*.*"^|find/v "%~x0"')do (set "_str=%%~nS" && (
      for /f %%n in ('cmd/u/cecho\"!_str!"^|find/v " "^|!_findstr!')do set "_n=!_n!%%~n" )
       2>nul rename "%%~S" "!_n!%%~xS" && echo\"%%~S" ==^> .\!_n!%%~xS && set "_n=" <nul ) 
    
    popd & %__APPDIR__%timeout.exe -1 & endlocal & goto :EOF
    
    • 对于此文件的路径/名称布局:
    G:\SUPER_USER\Q1533871\John Doe 123.txt
    G:\SUPER_USER\Q1533871\John Doe 1234.txt
    G:\SUPER_USER\Q1533871\John Junior Doe 00001.txt
    G:\SUPER_USER\Q1533871\John Junio Doe 154200 1 .txt
    
    • 代码结果/输出:
    G:\SUPER_USER\Q1533871\John Doe 123.txt ==> .\123.txt
    G:\SUPER_USER\Q1533871\John Doe 1234.txt ==> .\1234.txt
    G:\SUPER_USER\Q1533871\John Junior Doe 00001.txt ==> .\00001.txt
    G:\SUPER_USER\Q1533871\John Junio Doe 154200 1 .txt ==> .\1542001.txt
    
    • 如何在代码中实现更多任务...
    @echo off && setlocal EnableDelayedExpansion
    
    pushd "c:\path\to\your\files"
    set "_where=%__APPDIR__%where.exe" 
    set "_findstr=%__APPDIR__%findstr.exe [0-9]"
    
    for /f "tokens=*" %%S in ('!_where! .:"*.*"^|find/v "%~x0"')do (set "_str=%%~nS" && (
      for /f %%n in ('cmd/u/cecho\"!_str!"^|find/v " "^|!_findstr!')do set "_n=!_n!%%~n" )
       2>nul rename "%%~S" "!_n!%%~xS" && echo\"%%~S" ==^> .\!_n!%%~xS && set "_n=" <nul
    
       rem ::  Aditionals taks commands enter here bellow here....
    
       ) 
    
    popd & %__APPDIR__%timeout.exe -1 & endlocal & goto :EOF
    

    对于命令行帮助,您可以使用/?:

    Pushd /?, Popd /?, Find /?, Findstr /?, Ren /?, For /?, Setlocal /?, Endlocal /?, Goto /?, Setlocal /?, Endlocal /?, if /?, timeout /?, ... /?

    在互联网上,您可以获得更多帮助:

    • 流行音乐

    • 寻找

    • 推送

    • 在哪里

    • 对于 /f

    • 查找

    • 暂停

    • 设置本地

    • 本地化

    • 任 / 重命名

    • 转到:EOF

    • 启用延迟扩展

    • If, Else If, Else, If defined, Errorlevel ...

    对不起我有限的英语

    • 0

相关问题

  • 如何将变量字符串放入powershell中的数组?

  • Powershell 和正则表达式:Notepad++“保存时备份”文件列表。编辑名称,按上次写入时间排序

  • 将前景颜色添加到 Powershell 配置文件?

  • 禁用后无法启用 Microsoft Print to PDF

  • 我可以让这个 PowerShell 脚本接受逗号吗?

Sidebar

Stats

  • 问题 205573
  • 回答 270741
  • 最佳答案 135370
  • 用户 68524
  • 热门
  • 回答
  • Marko Smith

    如何减少“vmmem”进程的消耗?

    • 11 个回答
  • Marko Smith

    从 Microsoft Stream 下载视频

    • 4 个回答
  • Marko Smith

    Google Chrome DevTools 无法解析 SourceMap:chrome-extension

    • 6 个回答
  • Marko Smith

    Windows 照片查看器因为内存不足而无法运行?

    • 5 个回答
  • Marko Smith

    支持结束后如何激活 WindowsXP?

    • 6 个回答
  • Marko Smith

    远程桌面间歇性冻结

    • 7 个回答
  • Marko Smith

    子网掩码 /32 是什么意思?

    • 6 个回答
  • Marko Smith

    鼠标指针在 Windows 中按下的箭头键上移动?

    • 1 个回答
  • Marko Smith

    VirtualBox 无法以 VERR_NEM_VM_CREATE_FAILED 启动

    • 8 个回答
  • Marko Smith

    应用程序不会出现在 MacBook 的摄像头和麦克风隐私设置中

    • 5 个回答
  • Martin Hope
    CiaranWelsh 如何减少“vmmem”进程的消耗? 2020-06-10 02:06:58 +0800 CST
  • Martin Hope
    Jim Windows 10 搜索未加载,显示空白窗口 2020-02-06 03:28:26 +0800 CST
  • Martin Hope
    v15 为什么通过电缆(同轴电缆)的千兆位/秒 Internet 连接不能像光纤一样提供对称速度? 2020-01-25 08:53:31 +0800 CST
  • Martin Hope
    fixer1234 “HTTPS Everywhere”仍然相关吗? 2019-10-27 18:06:25 +0800 CST
  • Martin Hope
    andre_ss6 远程桌面间歇性冻结 2019-09-11 12:56:40 +0800 CST
  • Martin Hope
    Riley Carney 为什么在 URL 后面加一个点会删除登录信息? 2019-08-06 10:59:24 +0800 CST
  • Martin Hope
    zdimension 鼠标指针在 Windows 中按下的箭头键上移动? 2019-08-04 06:39:57 +0800 CST
  • Martin Hope
    jonsca 我所有的 Firefox 附加组件突然被禁用了,我该如何重新启用它们? 2019-05-04 17:58:52 +0800 CST
  • Martin Hope
    MCK 是否可以使用文本创建二维码? 2019-04-02 06:32:14 +0800 CST
  • Martin Hope
    SoniEx2 更改 git init 默认分支名称 2019-04-01 06:16:56 +0800 CST

热门标签

windows-10 linux windows microsoft-excel networking ubuntu worksheet-function bash command-line hard-drive

Explore

  • 主页
  • 问题
    • 最新
    • 热门
  • 标签
  • 帮助

Footer

AskOverflow.Dev

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve