.bat measure file path length and put it in a .txt-file

本小妞迷上赌 提交于 2020-01-25 23:40:25

问题


I'm trying to make a .bat file that will run through all files in a given folder, measure the length of the file+path and if its longer than eg. 50 characters the file and path are written into a .txt-file.

I'm pretty much a n00b, so not to advanced, and somewhat well explained ;).

im writing into a file with

echo %File% > filer.txt

Where File should contain the file name and path.

Edit: Im sorry, I was perhaps a bit unclear in my description of the task it should preform. What I ment was, loop trough files and subfolders of a given folder. and return in the document the files with a path longer than 50 including Drive and Filetype.


回答1:


As Dennis already noted, batch has no built-in solution for getting the lenght of the path. But if you only want to know, if a string is larger than n, just check, if there is a character at the n+1 position:

if "%string:~51,1%" neq "" echo %string% is longer than 50 characters

Much faster than counting characters.

Combined with Dennis' logic:

@echo off
setlocal EnableDelayedExpansion
(
  for %%g in ("*") do (
    set "File=%%~dpnxg"
    if "!File:~51,1!" neq "" echo !File!
  )
)>filer.txt

I put the whole for loop into another block to redirect only once to the output-file. this is much faster (>> would open the file, write one line and close the file, just to open it again etc...)




回答2:


You could use this:

@echo off
setlocal EnableDelayedExpansion
for %%g in ("*") do (
set "File=%%~dpnxg"
>x echo !File!&for %%? in (x) do set /a strlength=%%~z? - 2&del x
if !strlength! gtr 50 echo !File! >> filer.txt
)

This loops through all files in the current folder, and puts their drive, path, name and extension in the variable %File%. It then writes %File% to a temporary file x, and gets the stringlength from that, and deletes x. If the string length is greater than 50 it writes the name of the file to filer.txt.

You need the delayed expansion to work with variables inside loops.

Note, this code currently uses drive, path, filename and extension. Change the line set "File=%%~dpnxg" to change this behaviour ([d]rive, [p]ath, [n]ame, e[x]tension, the g is necesary)



来源:https://stackoverflow.com/questions/37525639/bat-measure-file-path-length-and-put-it-in-a-txt-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!