
Я хочу переместить часть имени файла в начало имени файла. Все мои файлы имеют разделитель #
, например: 2585#xxxxx#4157.pdf
.
Теперь я хочу переместить часть после последней #
во вторую часть имени файла, например:2585#4157#xxxxx.pdf
Как это сделать с помощью powershell? Я пока не рассматривал никаких методов сам, так как не знаю, что искать.
решение1
Нижеприведенный скрипт сделает то, что вы ищете. Он написан не таким уж лаконичным циклом, так что каждый шаг пути понятен. Есть более оптимальные способы написать этот скрипт.
# Assumes this script is run in the directory with the pdf files
# First get all pdf files in the current directory
$all_files = Get-ChildItem -Path . -Filter '*.pdf'
# Loop over all files
foreach ($file in $all_files) {
# Get the current (old) filename
$old_name = $file.Name
# Define a regex pattern (see below)
$regex_pattern = '(.+)#(.+)#(.+)(\.pdf)'
# Define a replacement pattern (see below)
$replace_pattern = '$1#$3#$2$4'
# Construct the new name
$new_name = $old_name -replace $regex_pattern, $replace_pattern
# Actually rename the file
Rename-Item -Path $file.FullName -NewName $new_name
}
Регулярное выражение
Регулярное выражение— это расширенный способ поиска (и замены) текста.
Шаблон поиска можно разбить на следующие части:
(.+) Match any character 1 or more times, store in the first group
# Match the # symbol literally
(.+) Match any character 1 or more times, store in the second group
# Match the # symbol literally
(.+) Match any character 1 or more times, store in the third group
(\.pdf) Match a literal dot followed by the letters "pdf" and store in the fourth group
Шаблон замены использует переупорядочивание сохраненных частей из шаблона поиска:
$1 Take the content from the first group
# Write a literal # symbol
$3 Take the content from the third group
# Write a literal # symbol
$2 Take the content from the second group
$4 Take the content from the fourth group
Запуск этого скрипта переименовывает следующие файлы:
2585#xxxxx#4157.pdf
2d23#ab23-421d#40++057.pdf
2d23#abd#400057.pdf
в
2585#4157#xxxxx.pdf
2d23#40++057#ab23-421d.pdf
2d23#400057#abd.pdf
решение2
В качестве альтернативы без регулярных выражений можно сделать так:
(Get-ChildItem -Path 'X:\where\the\files\are' -Filter '*#*#*.pdf' -File) |
Rename-Item -NewName {
$first, $second, $third = $_.BaseName.Split("#")
'{0}#{1}#{2}{3}' -f $first, $third, $second, $_.Extension
}