Sometimes I’d like to snip off the newline from the end of a file. But there’s no efficient way to do it using pure Batch commands. Recently, I unearthed a Super User question on how to truncate a set amount of bytes from a file. The second answer gave a PowerShell solution. I know nothing of PowerShell (except that it’s even uglier and more obtuse than VBScript ), but I managed to glue the following snippet together:
Code: Select all
@echo off & setlocal enableextensions
powershell -noprofile -command ^"^& {$file='%~dpf1'; $BYTES_TO_TRIM=%2; ^
$byteEncodedContent = [System.IO.File]::ReadAllBytes($file); ^
$truncatedByteEncodedContent = $byteEncodedContent[0..($byteEncodedContent.Length - ($BYTES_TO_TRIM + 1))]; ^
Set-Content -value $truncatedByteEncodedContent -encoding byte -path "$($file)"}"
endlocal & exit /b 0
Awful, isn’t it? But it has one redeeming quality… it works! The snippet accepts two parameters: a filename, and the number of bytes to be snipped off the end of the file. And the best bit is that the file is edited in place. Sweet! The last modified time is updated and creation time is preserved.
How does it work? Well, I think it slurps the whole file into an array, subtracts the number of bytes to be truncated from the array length, and writes the modified array back into the original file. Works fine with smallish files. I tried it on a 6Mb file and there was a delay of a few seconds.
Of course, you could just use the freeware and tiny (~6k) trunc command line utility. But many people find themselves in environments where they’re not allowed to install third party software. Plus, the snippet above is more flexible. It could easily be modified to truncate from the beginning of a file, or even the middle. With judicious use of findstr /o, a wily Batcher might even be able to delete a range of lines from a file without having to go through the rigmarole of looping through the file line by line, storing the head in a temporary file, deleting the range of lines, and gluing the head and tail back together. Tedious!
Anyways, please feel free to improve the functionality and efficiency of the code above. It would be interesting to see how far you gurus could run with this particular ball.
- SB