i have more than 200 files in a folder
JOB1_CostReport.xlsx
JOB2_CostReport.xlsx
JOB4_CostReport.xlsx
JOB3_CostReport.xlsx
JOB7_CostReport.xlsx
....
JOB196_CostReport.xlsx
JOB200_CostReport.xlsx
I want to reanme all these files with a suffix like this : JOB1_CostReport_Aug_2020.xlsx
I have tried : Get-ChildItem | rename-item -NewName { $_.Name + "_Aug_2020" }
the result was like this :
JOB1_CostReport.xlsx_Aug_2020
JOB2_CostReport.xlsx_Aug_2020
JOB4_CostReport.xlsx_Aug_2020
JOB3_CostReport.xlsx_Aug_2020
JOB7_CostReport.xlsx_Aug_2020
JOB196_CostReport.xlsx_Aug_2020
JOB200_CostReport.xlsx_Aug_2020
what I want is more like :
JOB1_CostReport_Aug_2020.xlsx
JOB2_CostReport_Aug_2020.xlsx
JOB4_CostReport_Aug_2020.xlsx
JOB3_CostReport_Aug_2020.xlsx
JOB7_CostReport_Aug_2020.xlsx
JOB196_CostReport_Aug_2020.xlsx
JOB200_CostReport_Aug_2020.xlsx
try this:
Get-ChildItem | rename-item -NewName { $_.BaseName + "_Aug_2020" + $_.Extension}
Besides #Brumor's excellent answer in powershell, and as you have tagged this question Cmd, so try this in a batch file:
for %%a in (*) do ren "%%~a" "%%~na_Aug_2020%%~xa"
PS when running in Cmd replace the %% to %.
All the given answers rename the files multiple times(rename the file for 100 times if there are 100 files in the folder and it will add the prefix 100 times).
Use the following command in cmd:
for /f "tokens=*" %a in ('dir /b') do ren "%a" "%%~na_Aug_2020%%~xa"
Related
I have some folders like
Computer Idea
confidenze fatali
Casa Naturale sette
and files like
2021-09-01 computer idea.rar
into confidenze fatali.pdf
casa naturale sette 454.jpg
I try to move in this way
Computer Idea
|
|---> 2021-09-01 computer idea.rar
confidenze fatali
|
|---> into confidenze fatali.pdf
Casa Naturale sette
|
|---> casa naturale sette 454.jpg
For example, composed word computer idea is found for both 2021-09-01 computer idea.rar file and Computer Idea folder (in this situation we have same 2 adjacent words). Delimitator for composed word is simply an empty space.
I try to use this batch script but doesn't work, I ask also for a powershell solution so I add that tag in question.
#Echo off
Pushd %1
For /d %%A in (*) do For /f "delims=" %%B in (
'Dir /B "*%%~nxA*" 2^>Nul '
) do If "%%~nxA" NEQ "%%~nxB" Move "%%~fB" "%%~fA\" 2>&1>>Nul
Popd
With PowerShell you do:
$rootFolder = 'D:\Test'
# get a list of folders inside the root folder
$subFolders = Get-ChildItem -Path $rootFolder -Directory
# next loop through the folders and find files that match their names
foreach ($folder in $subFolders) {
# use the foldername as filter, surrounded with wildcard characters (*)
Get-ChildItem -Path $rootFolder -Filter "*$($folder.Name)*" -File | Move-Item -Destination $folder.FullName -WhatIf
}
The -WhatIf switch is a safety switch which will only show on screen what files would be moved without actually moving anything. If you find that info is correct, remove the -WhatIf switch from the code and run again.
I'm 99.9% sure there is a better way of doing this, but here's my take:
Get-ChildItem -Path "C:\Path" | Sort-Object -Property "Mode" |
ForEach-Object -Begin {
$files = #{}
} -Process {
if (-not $_.PSIsContainer) {
$files.Add($_.Name,$_.FullName) | Out-Null
}
else {
$folder = $_
$files.GetEnumerator() | ForEach-Object -Process {
if ($_.Key -match $folder.Name) {
Move-Item -Path $_.Value -Destination $folder.FullName -WhatIf
}
}
}
}
Since they are all located in the same directory, you can filter out which one is a file and which one is a folder by sending the files to a hashtable first; this is why we used Sort-Object to organize by filetype listing files at the top. With the files being processed first in our if statement, we know our else block (really not needed) will contain just folders. Finally, we can enumerate our hashtable in order to match file names to folder names. All that's left to do is move the files to their corresponding folder.
Remove the -WhatIf common parameter when you've determined the results displayed are what you're after to perform the actual move.
For /d %%A in (*) do Move "*%%A*" "%%A\" 2>&1>>Nul
Should work - Try it on a test directory first.
Given further information that some target directory names may be substrings of others...
#ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
rem The following setting for the source directory is a name
rem that I use for testing and deliberately include names which include spaces to make sure
rem that the process works using such names. These will need to be changed to suit your situation.
SET "sourcedir=u:\your files"
PUSHD "%sourcedir%"
:: remove variables starting #
FOR /F "delims==" %%b In ('set # 2^>Nul') DO SET "%%b="
FOR /f "tokens=1*delims=:" %%b IN ('dir /b /ad ^|findstr /n .') DO SET "#%%b=%%c"&SET /a count=%%b
:: find a directory that is not a substring of another & process it
:reselect
FOR /L %%b IN (1,1,%count%) DO IF DEFINED #%%b (
SET "targetstring=!#%%b!"
FOR /L %%c IN (%%b,1,%count%) DO IF %%b neq %%c IF DEFINED #%%c (FOR %%e IN ("!#%%b!") DO IF /i "!#%%c:%%~e=!" neq "!#%%c!" SET "targetstring=")
IF DEFINED targetstring (
SET "#%%b="
FOR /f "delims=" %%c IN ('dir /b /a-d "*!targetstring!*" 2^>nul') do Move "%%c" "!targetstring!\"
GOTO reselect
)
)
POPD
First, find the directorynames and store them in variable #1..#whatever by submitting them to findstr /n which prefixes each with serial:
Next, repeated scan the array of #n variables, using targetstring as a store of the string being examined. Compare it to each other string in the array and if it's a substring of another, clear targetstring so if targetstring survives, clear the #variable that has this value, process the value and start over.
Repeat until all #variables have been processed - which means they are all deleted from the environment.
From this answer I can create multiple files a.txt, b.txt, ... , z.txt. in Bash with:
touch {a..z}.txt
Or 152 with:
touch {{a..z},{A..Z},{0..99}}.txt
How can I do this in Powershell?
I know New-Item a.txt, but If I want multiple files as above?
For curiosity, what are the equivalent commands in Command Prompt (cmd.exe)?
For Powershell:
1..5 | foreach { new-item -path c:\temp\$_.txt }
The foreach loop will run for each number in 1 to 5, and generate a file in the desired path with the name of that number passed to the command (represented by the $_)
You could also write it as:
%{1..5} | new-item c:\temp\$_.txt
For cmd:
for /L %v in (1,1,5) do type nul > %v.txt
More information here: cmd/batch looping
Not quite as concise as bash, but it can be done.
#(97..(97+25)) + #(48..(48+9)) |
ForEach-Object { New-Item -Path "$([char]$_).txt" -WhatIf }
Another way...
#([int][char]'a'..[int][char]'z') + #([int][char]'0'..[int][char]'9') |
ForEach-Object { New-Item -Path "$([char]$_).txt" -WhatIf }
And one more...
function rng { #($([int][char]$args[0])..$([int][char]$args[1])) }
(rng 'a' 'z') + (rng '0' '9') |
ForEach-Object { New-Item -Path "$([char]$_).txt" -WhatIf }
If you are desperate to do this in a cmd.exe shell, this might work. When it looks like the correct commands are produced, delete or comment out the echo line and remove the rem from the next line.
#ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
SET "CLIST=abcdefghijklmnopqrstuvwxyz0123456789"
FOR /L %%i IN (0,1,35) DO (
CALL SET "S=%%CLIST:~%%i,1%%.txt"
echo TYPE NUL ^>"!S!"
rem TYPE NUL >"!S!"
)
#Emilson Inoa Your solution is very ingenuous; there's a typo in the names, am sure you meant to exclude the extensions in the array. You'll end up with
("Text1", "Text2", "Text3") | % {ni -Path "/path/to/dir" -Name "$_.txt"}
For letters, in PowerShell, use:
97..( 97+25 ) | foreach { new-item $env:temp\$( [char]$_ ).txt }
Very simple, take a look:
("Text1.txt","Text2.txt", "Text3.txt") | foreach { New-Item -Path "X" -Name "$_.txt" }
You will replace X of course with the path where you want the files to be created.
If further explanation is required, let me know.
The following command in powershell will create multiple files (20) named Doc_.txt in the directory that the command is executed.
new-item $(1..20 | %{"Doc$_.txt"})
I think this command is the closest to the bash equivalent:
touch Doc{1..20}.txt
This doesn't directly answer your question (as this method requires each file extension be provided), but a more rudimentary way is of course:
New-Item {a..z}.txt, {A..Z}.txt, {0..9}.txt
After a few failed attempts, I mashed a couple of the answers above to create files titled [char][int].txt: 1..5 | foreach {New-Item -Path 'X' -Name "abc$_.txt"}, where X is the path. Also, just to thank the original writer of the question, as it described really succinctly exactly the problem I was trying to solve.
1..1000000 | foreach {new-item -path C:\Testdata$_.txt}
This worked fine for me. Created 1M files in the C:\Testdata folder.
In the PowerShell, you can use New-Item
New-Item a.txt, b.txt, c.txt
then hit Enter
I download some pdf files from HERE
Pdf files are downloaded not using original filenames but by number strings like
1610.00005
1610.00022
Fortunally in this HTTP link page or txt files (if I copy for offline renaming) I have relative
numeric -> original text filename
string corrispondence
For example when I download this files
- A Note on Time Operators in Relativistic Quantum Mechanics
- A Stronger Theorem Against Macro-realism
- Determining quantum correlations in bipartite systems - from qubit to qutrit and beyond
- Pair entanglement in dimerized spin-s chains
Files are downloaded with this filenames
1610.00005.pdf
1610.00022.pdf
1610.00041.pdf
1610.00056.pdf
BUT I want rename into original filesname not in a number string
I'd like to set a http link or text file for path
I have only this codes (powershell)
$names = Get-Content c\myfiles
Get-ChildItem C:\somedir\*.pdf | Sort -desc |
Foreach {$i=0} {Rename-Item $_ ($_.basename + $names[$i++] + $_.extension) -WhatIf}
or batch code
#echo off
setlocal EnableDelayedExpansion
rem Load the list of authors:
set i=0
for /F %%a in (myfiles.txt) do (
set /A i+=1
set "author[!i!]=%%a"
)
rem Do the rename:
set i=0
for /F %%a in ('dir /b *.pdf') do (
set /A i+=1
for %%i in (!i!) do ren "%%a" "%%~Na!author[%%i]!%%~Xa"
)
#All PDFs | Rename { query Arxiv for the abstract by filename, use the page title + ".pdf"}
Get-ChildItem *.pdf | Rename-Item -NewName {
$title = (Invoke-WebRequest "https://arxiv.org/abs/$($_.BaseName)").parsedhtml.title
$title = $title -replace '[\\/:\*\?"<>\|]', '-' # replace forbidden characters
"$title.pdf" # in filenames with -
}
You might want to put a -whatif on the end first, to see what it would do, in case it ruins all the filenames. Or take a backup copy of the folder.
Edit: One of the titles is "Signatures of bifurcation on quantum correlations: Case of quantum kicked top" and the : is not allowed in a filename. Script edited to replace all forbidden characters in Windows filenames with dashes instead.
I have a lot of files named like
Files_01(some text).png
Files_02(some different text).png
Files_03(some other text).png
Files_04(totally different text).png
What I'm looking for is a way to remove everything in the brackets so that I'm left with:
Files_01.png
Files_02.png
etc.
I tried the following, but it didn't remove the text in parentheses:
Get-ChildItem .png | foreach {
Rename-Item $_ $_.Name.Replace("()", "")
}
This is how I completed the task. I read in the file objects from the directory, then check if the filename contains parentheses. If the name does, I replace the parentheses and any text in between with an empty string. Then call Rename-Item and pass it the new file name without the parentheses.
Get-ChildItem -Path C:\PowershellTest\ | % {if($_.Name -match '.*\(.*\).*') {Rename-Item -Path $_.FullName -NewName $($_.Name -replace '\(.*\)', '')}}
Try like this :
#echo off
set "$ext=.png"
for /f "delims=" %%b in ('dir /b/a-d *%$ext%') do for /f "tokens=1 delims=()" %%c in ('echo %%b') do ren "%%~nb%$ext%" "%%~nc%$ext%"
In powershell I'd probably create something like this:
$myFolder = "C:\Users\Aarron\Pictures\"
Foreach ($file in Get-Childitem $myFolder\*.png)
{
$ReName = $file.basename.split("(")[0] + $file.extension
Rename-Item $file.FullName $ReName
}
…and a possible batch solution:
#Echo Off
Set "myFolder=C:\Users\Aarron\Pictures\"
For %%A In ("%myFolder%\*.png") Do Call :Sub "%%~dpA" "%%~nA" "%%~xA"
Exit/B
:Sub
Set "ReName=%~2"
Set ReName=%ReName:(=&:%
Ren "%~1%~2%~3" "%ReName%%~3"
first of all: I'm on a Windows 7 machine ;).
I got a folder with several dozens files. Each file contains about 240.000 rows. But only half of that rows are needed.
What I would like to do is: have a script that runs over these files, filters out every row that contains the string "abcd" and have it either saved in a new directory or just saved in the same file.
I would try using Powershell as below:
$currentPath = "the path these files currently in"
$newPath = "the path you want to put the new files"
$files = Get-ChildItem $currentPath
foreach ($item in $files) {
Get-Content $item | Where-Object {$_ -notmatch 'abcd'} |Set-Content $newPath\$item
}
#echo off
setlocal enableextensions
set "_where=c:\some\where\*.txt"
set "_filter=abcd"
rem find files which needs filter
for /f "tokens=*" %%f in ('findstr /m "%_filter%" "%_where%"') do (
rem generate a temporary file with the valid content
findstr /v /c:"%_filter%" "%%~ff" > "%%~ff.tmp"
rem rename original file to .old
ren "%%~ff" *.old > nul
rem rename temporary file as original file
ren "%%~ff.tmp" "%%~nxf" > nul
)
rem if needed, delete *.old files
you might use sed for Windows
sed -i.bak "/abcd/!d" *.txt
Find all abcd containing rows in .txt files, make a backup file .bak and store the the detected lines in the original file.
#echo on
For %%a in (*.txt) do (CALL:FILTER "%%a")
echo/Done.&pause>nul&exit/b
:FILTER
type "%~1"|find "abcd" 1>nul 2>nul
if %errorlevel% EQU 0 find /n "abcd" "%~1">"Found abcd in %~1.txt"
The command Find returns error level = 0 if him find something
If the files are that big, I'd so something like this:
$Folder = 'C:\MyOldFiles'
$NewFolder = 'C:\MyNewFiles'
New-Item -ItemType Directory -Path $NewFolder -Force
foreach ($file in Get-ChildItem $Folder)
{
Get-Content $file -ReadCount 1500 |
foreach { $_ -notmatch 'abcd' } |
Add-Content "$NewFolder\$($file.name)"
}