I want to read all the .log files for todays file timestamp (i.e today's date yyyymmdd) in a folder which contains a string "scp error". And if condition satisfies move the name of .log file without extension to a new .txt file "redrop_files.txt"
this is what I have tried so far
Get-Item File*.log | ForEach-Object {
$fil = $_.Name;
foreach ($line in Get-Content $fil) {
if ($line -eq "scp error") {
$stat = "FAILED"
}
}
if ($stat -eq "FAILED") {
$errorfile = Get-ChildItem *.log | Rename-Item -NewName { $fil -replace '.log','' }
Add-Content -Path .\redrop_files.txt "`n" $errorfile
}
}
CodePudding user response:
You have one main problem: you don't store the results of grep
anywhere so variable f
is undefined.
It is not clear why you use -n
with grep if you only want the filename; -l
seems to make more sense.
So:
grep --include=\*.log -rlw '/path/' -e "scp error" |\
while read -r f; do
echo "${f%%.*}"
done > redrop_files.txt
CodePudding user response:
Try the following,
path=.
while read file; do
echo ${file%%:*} >> redrop_files.txt
done < <(grep --include=\*.log -rnw $path -e "scp error")
CodePudding user response:
Your code has some minor mistakes, and a few improvements you could use, for example using a switch
to read the files. The biggest problem is that you're actually renaming the files, Rename-Item
actually renames files. What you want to do instead is append the .BaseName
property (the file name without its extension) to your redrop_files.txt
file.
Get-Item File*.log | ForEach-Object {
# if this file is not from Today
if($_.CreationTime -lt [datetime]::Today) {
# skip it
return
}
$append = switch -Wildcard -File $_.FullName {
# if the line contains "scp error"
'*scp error*' {
# output true
$true
# and break this loop, no need to keep checking
break
}
}
# if the result of the switch loop was true
if ($append) {
# append to redrop_files.txt the .BaseName of this file
Add-Content -Value $_.BaseName -Path .\redrop_files.txt
}
}