简体   繁体   中英

How can I make this perl command check for subfolders as well?

I'm running Windows 10 and I have a batch file that changes the directory to the required location and a perl command that edits all text files in it by changing Enabled = 1 to Enabled = 0, but I can't figure out how to make the perl command check for subfolders.

@echo off
timeout 1 >nul 2>&1
cd /d D:
timeout 1 >nul 2>&1
cd "D:\MySettings"
timeout 1 >nul 2>&1
perl -wE "@ARGV = glob qq($ARGV[0]); $^I = qq(); while (<>) { s/Enabled =\K.*/ \x220\x22/g; print }" *.txt
Pause

To process files in subfolders as well, and (I presume) in sub-sub-folders, etc, that list of all "entries" ( glob ) need be split into files and folders. Edit the files and repeat the process in subfolders. This is often done recursively but there are other ways. It's a little job to do.

And there are libraries for recursive traversal and processing, of course. For example the core File::Find (or File::Find::Rule ), or Path::Iterator::Rule . But since you also need to edit each file in a simple manner let's look at a more general utility Path::Tiny , which has a few methods for editing files in-place, as well.

If you insist on a command-line program ("one-liner")

perl -MPath::Tiny -we"
    path(qq(.))->visit( sub { 
        my ($entry, $state) = @_; 
        return if not -T;
        path($entry)->edit_lines( sub { s/.../.../g } )
    }, 
    { recurse => 1 }
)"

Here the visit method executes the sub { } callback on each entry under the given folder, and goes on recursively (with that option). We skip entries which aren't ASCII or UTF-8 files, by -T filetest .

Inside the callback, edit_lines processes each line of the file as specified in its sub ; in this case, run the regex from the question. Once it's done with the whole file it replaces the original with the edited version. See docs.

For this, I think it could be only done by perl commands, not in batch commands.

You can check here for more specific solutions

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM