在 Notepad++ 中将文本数字替换为文件名
Replace text numbers as file name in Notepad++
我需要用文件名编号替换文本中包含的一些数字,例如:
文件名:文本-3.txt
- 文本 bla bla bla,aaaa ...
替换那个数字“1”。通过数字 3,包含在文件名中。并删除那个“。”留下来了。
我为您组装了这个 powershell。我添加的评论中描述了正在发生的事情。注释以“#”开头。如果您的文件名约定与 'text-1.txt' 示例不同,那么您必须将此行修改为适当的名称约定 $target_files = gci $working_dir\* -include 'text*.txt'
-特别是 -include
参数中的内容。
如果需要,只需更新此脚本中的 $working_dir
变量以适合您正在使用的目录。
# where to look for files
$working_dir = "C:\Users\userNameHere\Desktop\Folder123"
# Find the files with get-childitem, put into variable.
$target_files = gci $working_dir\* -include 'text*.txt'
# For every file, do the following
foreach($file in $target_files){
# Read the file content with get-content
$file_content = gc $file -raw
# Create regex pattern to find the number for replacing
$reg_pattern = '^.*\d+[.]'
# Get the number out of the filename.
$file.Name -match "\d+" | Out-null
[int]$file_number = $matches[0]
# If we find a Number followed by a period in the content, replace it with the number we found in the filename
if($file_content -match $reg_pattern){
$file_content -replace $matches[0],$file_number | sc $file
}
}
将其粘贴到记事本中,执行文件> 另存为> 并将 "Filetype" 的下拉菜单更改为 All Files (*.*)
。输入您将命名的脚本,然后输入 .ps1
文件扩展名。这会将其保存为 powershell 文件。然后您将右键单击该文件并 "Run with Powershell".
我需要用文件名编号替换文本中包含的一些数字,例如:
文件名:文本-3.txt
- 文本 bla bla bla,aaaa ...
替换那个数字“1”。通过数字 3,包含在文件名中。并删除那个“。”留下来了。
我为您组装了这个 powershell。我添加的评论中描述了正在发生的事情。注释以“#”开头。如果您的文件名约定与 'text-1.txt' 示例不同,那么您必须将此行修改为适当的名称约定 $target_files = gci $working_dir\* -include 'text*.txt'
-特别是 -include
参数中的内容。
如果需要,只需更新此脚本中的 $working_dir
变量以适合您正在使用的目录。
# where to look for files
$working_dir = "C:\Users\userNameHere\Desktop\Folder123"
# Find the files with get-childitem, put into variable.
$target_files = gci $working_dir\* -include 'text*.txt'
# For every file, do the following
foreach($file in $target_files){
# Read the file content with get-content
$file_content = gc $file -raw
# Create regex pattern to find the number for replacing
$reg_pattern = '^.*\d+[.]'
# Get the number out of the filename.
$file.Name -match "\d+" | Out-null
[int]$file_number = $matches[0]
# If we find a Number followed by a period in the content, replace it with the number we found in the filename
if($file_content -match $reg_pattern){
$file_content -replace $matches[0],$file_number | sc $file
}
}
将其粘贴到记事本中,执行文件> 另存为> 并将 "Filetype" 的下拉菜单更改为 All Files (*.*)
。输入您将命名的脚本,然后输入 .ps1
文件扩展名。这会将其保存为 powershell 文件。然后您将右键单击该文件并 "Run with Powershell".