Windows批处理命令快速获取文件夹下特定类型的文件名(2022.5.15)

1、需求分析

        在日常的学习和工作中,可能大家或多或少会遇到这样一个问题:对于电脑文件资源管理器中的某个文件夹,该文件夹下包含许多不同类型的文件,此时自己想要立刻获取某种特定类型对应的全部文件名。当然,不可否认的是,我们自然是可以找到很多种方法来解决这个问题,但关键在于如何简单直接、快速而又高效地完成这个任务呢?

2、batch简介

        batch批处理是一种脚本语言,可称为,用于对一些对象进行批处理流程化的操作,任何操作系统中可运行的执行程序都可以放到批处理文件中来运行。常见的批处理主要包含DOS批处理和PowerShell批处理,另外很多专业软件通常也内置有批处理功能,目的是便于用户进行自动化操作
        在Windows系统中,批处理命令可由PowerShellcmd窗口来解释运行,对应的批处理文件扩展名一般为.cmd和.bat
        批处理文件称为批处理程序,是由一条条的DOS命令组成的普通文本文件,可以用Notepad直接编辑或用DOS命令创建,也可以用DOS下的文本编辑器Edit.exe来编辑。在cmd prompt键入批处理文件的名称或者直接双击批处理文件,操作系统就会调用Cmd.exe运行该批处理程序。

cmd文件
bat文件

3、代码实现

        对普通用户而言,当搜索结果较少时,自己可以手动逐个复制并粘贴文件名,但这样做效率低、速度慢、容易导致错误,且手工劳动量会随搜索结果数目的增多而显著增加;而对于程序员和开发者而言,大抵是利用现有的编程语言(C++、Python、Java、C#、Matlab、C、VB等)编写执行程序,那么无论采用何种编程语言,都要经历三个步骤:配置环境、编写代码、编译运行,最终获得程序执行的结果。这里推荐大家利用Windows系统自带的批处理命令脚本来实现,因为无需任何环境配置,简单直接,十分高效,只需熟悉常用的Shell命令即可。
        如下图所示,给出一个实例,在D:\test文件夹包含多种不同格式类型的文件,如.txt文本文件、.jpg图片文件、.pdf、.json数据文件、.xlsx表格文件、.docx文档文件、.pptx演示文稿文件、.mp4视频文件等.
在这里插入图片描述

3.1 八种编程语言分别实现

        这里分别利用C#、C++、Java、Python、Matlab、C、Scala、VB八种编程语言来实现文件夹下特定文件类型的搜索功能

3.1.1 C# 实现

        利用Microsoft Visual Studio 2015编写C#程序实现,具体代码和运行结果如下。
Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace GetFileNameWithSpecificSuffix
{
    
    
    class Program
    {
    
    
        static void Main(string[] args)
        {
    
    
            while (true)
            {
    
    
                string path = "", suffix_name = "";//所要查找的文件夹、要搜索的文件后缀名
                Console.WriteLine("************获取文件夹下特定类型文件的文件名*************(Enter键退出)!");
                Console.Write("请输入要搜索的文件目录(如 D:\\test):");
                path = Console.ReadLine();
                Console.Write("请输入要搜索的文件后缀名(如*.txt):");
                suffix_name = Console.ReadLine();
                if (path != "" && Directory.Exists(path))//文件目录不为空且文件夹存在
                {
    
    
                    DirectoryInfo folder = new DirectoryInfo(path);
                    if (suffix_name == "")
                    {
    
    
                        foreach (FileInfo file in folder.GetFiles())
                        {
    
    
                            Console.WriteLine(file.Name);
                        }
                    }
                    else
                    {
    
    
                        foreach (FileInfo file in folder.GetFiles(suffix_name))
                        {
    
    
                            Console.WriteLine(file.Name);
                        }
                    }
                }
                else
                {
    
    
                    Console.WriteLine("文件目录不存在,退出!");
                    break;//退出程序
                }
            }
        }
    }
}

在这里插入图片描述
在这里插入图片描述

3.1.2 C++ 实现

        利用VS 2015编写C++程序实现,具体代码和运行结果如下。
main.cpp

#include <iostream>
#include <io.h>
using namespace std;

#define MAX_FILENAME_LENGTH 500
#define MAX_SUFFIX_LENGTH 6

void getFiles(char *path, char *suffixname)
{
    
    
	__int64  hFile = 0;
	struct _finddata_t singlefileinfo;
	const char* str_add = "\\*";
	size_t len3 = strlen(str_add),len_path = strlen(path);
	for (size_t i = 0; i <len3; i++)
	{
    
    
		path[i + len_path] = str_add[i];
	}
	if ((hFile = _findfirst(path, &singlefileinfo)) != -1)	//string p; p.assign(path).append("\\*").c_str() 替代此行的path
	{
    
    
		do
		{
    
    
			if ((singlefileinfo.attrib & _A_SUBDIR))
			{
    
    
				if (strcmp(singlefileinfo.name, ".") != 0 && strcmp(singlefileinfo.name, "..") != 0)
					continue;
			}
			else
			{
    
    
				size_t length = strlen(singlefileinfo.name);
				char *filename = singlefileinfo.name;
				size_t pos_lastdot = -1;
				for (size_t j = length - 1; j>0; j--)
					if (filename[j] == '.')
					{
    
    
						pos_lastdot = j;
						break;
					}
				if (pos_lastdot != -1)
				{
    
    
					size_t actualsuffix_len = length - pos_lastdot;
					if (actualsuffix_len == strlen(suffixname))
					{
    
    
						char actualsuffix[MAX_SUFFIX_LENGTH];
						memcpy(actualsuffix, filename + pos_lastdot, actualsuffix_len);
						int flag = 1;
						for (int k = 0; k<actualsuffix_len; k++)
							if (actualsuffix[k] != suffixname[k])
							{
    
    
								flag = -1; break;
							}
						if (flag == 1)
							cout<< filename<< endl;
					}
				}
			}
		} while (_findnext(hFile, &singlefileinfo) == 0);
		_findclose(hFile);
	}
}

int main(int argc, char **argv)
{
    
    
	while (true)
	{
    
    
		char path[MAX_FILENAME_LENGTH], suffixname[MAX_SUFFIX_LENGTH];
		printf("*************查找指定文件夹下具有特定扩展名的所有文件***************\n");
		cout << "请输入要搜索的文件夹(如D:\\test):";
		cin >> path;
		cout << "请输入文件后缀名(如.jpg、.json、.md、.pdf、.xlsx、.pptx、.vsdx、.docx、.mp4、.bat、.txt):";
		cin >> suffixname;
		if (strlen(path) < 4 || strlen(suffixname) < 3)
			break;
		getFiles(path, suffixname);
	}
	return 0;
}

在这里插入图片描述

3.1.3 java 实现

        利用Eclipse编写Java程序实现,具体代码和运行结果如下。
GetFIleNameBySuffix.java

package com;

import java.io.File;

public class GetFileNameBySuffix 
{
    
    
	public static void printFileNameBySuffix(String path,String suffixname)
	{
    
    
		System.out.println(path+"文件夹下后缀名为"+suffixname+"的文件:");
		File file = new File(path);		//获取其file对象
		File[] fs = file.listFiles();
		for(File f:fs)
		{
    
    
			String filename = f.getName();
			if(f.isFile() && filename.endsWith(suffixname))
			    System.out.println(filename);
		}
	}
	
	public static void main(String[] args)
	{
    
    
		String folder = "D:\\test";
		String[] suffixname_list = {
    
    ".jpg", ".json", ".md", ".pdf", ".xlsx", ".pptx", ".vsdx", ".docx", ".mp4", ".bat", ".txt"};
		for(int i=0;i<suffixname_list.length;i++)
		{
    
    
			printFileNameBySuffix(folder, suffixname_list[i]);
		}
	}
}

在这里插入图片描述

3.1.4 Python 实现

        利用PyCharm编写Python程序实现,具体代码和运行结果如下。
GetFileNameBySuffix.py

import os

def getsuffixoffile(filename): # 获取文件对应字符串后缀名的函数
    res = ''
    lastdot_index = -1
    for i in range(0, len(filename)):
        if filename[i] == '.':
            lastdot_index = i
    if lastdot_index != -1:
        res += filename[lastdot_index:len(filename)]
    return res

def getFileNameBySuffixname(file_dir, suffix_name): # 获取某文件夹下特定后缀名的所有文件名
    filelist = []
    for root, dirs, files in os.walk(file_dir):
        for file in files:
            if getsuffixoffile(file) == suffix_name:
                filelist.append(file)
    return filelist

def shuchu(filelist):
    for x in filelist:
        print(x)

if __name__ == "__main__":
    file_dir = 'D:\\test'
    suffixname_list = ['.jpg', '.json', '.md', '.pdf', '.xlsx', '.pptx', '.vsdx', '.docx', '.mp4', '.bat', '.txt']
    for i in range(0, len(suffixname_list)):
        suffix_name = suffixname_list[i]
        print('**************'+file_dir + '文件夹下后缀名为'+suffix_name+'的文件*******************')
        result = getFileNameBySuffixname(file_dir, suffix_name)
        shuchu(result)

在这里插入图片描述
在这里插入图片描述

3.1.5 Matlab 实现

        利用Matlab R2021a编写脚本实现,具体代码和运行结果如下。

folder = 'D:\test';
suffixnamelist = {
    
    '.jpg', '.json', '.md', '.pdf', '.xlsx', '.pptx', '.vsdx', '.docx', '.mp4', '.bat', '.txt'};
filelist = dir(folder);
for i=1:1:length(suffixnamelist)
    suffixname = suffixnamelist{
    
    1,i};
    fprintf(['**************',folder,'文件夹下后缀名为',suffixname,'的文件**************','\n']);
    for j=1:1:length(filelist)
      if filelist(j).isdir == 0 && isSuffix(filelist(j).name,suffixname)
          fprintf([filelist(j).name,'\n'])
      end
    end
end

function [flag] = isSuffix(filename, suffix)%判断字符串以某个字符串结尾
    flag = 0;
    len1 = strlength(filename);
    len2 = strlength(suffix);
    suf_filename = filename(len1-len2+1:len1);
    if strcmpi(suf_filename,suffix)
        flag = 1;
    end
end

在这里插入图片描述
在这里插入图片描述

3.1.6 C 实现

        利用CodeBlocks编写C程序实现,具体代码和运行结果如下。
main.c

#include <stdio.h>
#include<io.h>
#define MAX_FILENAME_LENGTH 500

void getFiles(char *path, char *suffixname)
{
    
    
	long   hFile = 0;
	struct _finddata_t singlefileinfo;
	strcat(path, "\\*");
	if ((hFile = _findfirst(path, &singlefileinfo)) != -1)
	{
    
    
		do
		{
    
    
			if ((singlefileinfo.attrib & _A_SUBDIR))
			{
    
    
				if (strcmp(singlefileinfo.name, ".") != 0 && strcmp(singlefileinfo.name, "..") != 0)
					continue;
			}
			else
			{
    
    
				int length = strlen(singlefileinfo.name);
				char *filename = singlefileinfo.name;
				int pos_lastdot = -1;
				for(int j=length-1;j>0;j--)
                    if(filename[j] == '.')
                    {
    
    
                        pos_lastdot = j;
                        break;
                    }
                if (pos_lastdot != -1)
                {
    
    
                    int actualsuffix_len = length - pos_lastdot;
                    char actualsuffix[actualsuffix_len];
                    if (actualsuffix_len == strlen(suffixname))
                    {
    
    
                        memcpy(actualsuffix,filename + pos_lastdot,actualsuffix_len);
                        int flag = 1;
                        for(int k=0;k<actualsuffix_len;k++)
                            if(actualsuffix[k] != suffixname[k])
                            {
    
    
                                flag = -1;break;
                            }
                        if(flag == 1)
                            printf("%s\n",filename);
                    }
                }
			}
		} while (_findnext(hFile, &singlefileinfo) == 0);
		_findclose(hFile);
	}
}

int main()
{
    
    
    while(1)
    {
    
    
        printf("*************查找指定文件夹下具有特定扩展名的所有文件***************\n");
        printf("请输入要搜索的文件夹(如D:\\test):");
        char path[MAX_FILENAME_LENGTH];
//        scanf("%s",path);
        char *str1 = gets(path);
        char suffixname[6];
        printf("请输入文件后缀名(如.jpg、.json、.md、.pdf、.xlsx、.pptx、.vsdx、.docx、.mp4、.bat、.txt):");
//        scanf("%s",suffixname);
        char *str2 = gets(suffixname);
        if(strlen(str1) < 4 || strlen(str2) < 3)
            break;
        getFiles(path,suffixname);
    }
    return 0;
}

在这里插入图片描述
在这里插入图片描述

3.1.7 Scala 实现

        利用IDEA编写Scala程序实现,具体代码和运行结果如下。
TestGetFileNameBySuffix.scala

import java.io.File

object TestGetFileNameBySuffix
{
    
    
  def main(args: Array[String]): Unit =
  {
    
    
    val dir : String = "D:\\test";
    var suffixname_list = Array(".jpg", ".json", ".md", ".pdf", ".xlsx", ".pptx", ".vsdx", ".docx", ".mp4", ".bat", ".txt");
    val file: File = new File(dir);
    val files = file.listFiles(_.isFile());//仅搜索文件,不搜索文件夹
    var i = -1;
    for(i <- 0 to (suffixname_list.length-1) )
    {
    
    
      println("************"+dir + "文件夹下后缀名为" + suffixname_list(i) + "的文件************");
      var suffixname : String= suffixname_list(i);
      var j = -1;
      for(j <- 0 to (files.length-1) )
      {
    
    
        var filename:String = files(j).getName();
        if (filename.endsWith(suffixname))
        {
    
    
          println(filename);
        }
      }
    }
  }
}

在这里插入图片描述
在这里插入图片描述

3.1.8 VB 实现

        利用VS2015编写VB程序实现,具体代码和运行结果如下。
Module1.vb

Module Module1
    Sub Main()
        Dim folder As String = "D:\test"
        Dim suffixnamelist As String() = New String() {
    
    ".jpg", ".json", ".md", ".pdf", ".xlsx", ".pptx", ".vsdx", ".docx", ".mp4", ".bat", ".txt"}
        Dim fso, fo, fis, fi
        fso = CreateObject("Scripting.FileSystemObject")
        fo = fso.GetFolder(folder) '输入指定目录
        fis = fo.Files
        For i = 0 To suffixnamelist.Length - 1
            Dim suffixname As String = suffixnamelist(i) '从后缀名列表中获取后缀名
            Console.WriteLine("**************" + folder + "文件夹下后缀名为" + suffixname + "的文件**************")
            For Each fi In fis
                Dim filename As String = fi.Name
                If filename.EndsWith(suffixname) Then
                    Console.WriteLine(filename)
                End If
            Next
        Next
    End Sub
End Module

在这里插入图片描述

3.2 Windows批处理脚本实现

        在Windows操作系统中,可以打开cmd窗口或者PowerShell窗口来执行Windows批处理脚本(命令),输入help可查看相关指令的帮助。另外也可到微软官网查看cmd文档。之后给出两种实现方法来获得文件夹下特定后缀名的文件名,推荐使用第二种方法在配置opencv、eigen、osg等库的dll、lib和h文件时经常需要用到,较为直接)。

cmd窗口
PowerShell窗口

        第一种方式(包含其他附加信息):在目标文件夹D:\test下同时按住Shift鼠标右键打开cmd命令行窗口,

dir D:\test\*.txt > listtxtfilename.txt # 生成一个txt文件,里面包含txt为后缀名的文件名(同理可利用*.jpg等)

        第二种方式(仅文件名):在目标文件夹D:\test下新建两个bat文件,分别命名为test.batrun.bat后,输入如下代码,完成后双击run.bat即可运行代码。
test.bat

@echo off
if not exist *.jpg (
echo This directory contains no text files.
) else (
   echo ********This directory contains the following jpg files********
   echo.
   dir /b *.jpg
   )
if not exist *.json (
echo This directory contains no text files.
) else (
   echo ********This directory contains the following json files********
   echo.
   dir /b *.json
   )
if not exist *.md (
echo This directory contains no text files.
) else (
   echo ********This directory contains the following md files********
   echo.
   dir /b *.md
   )
if not exist *.pdf (
echo This directory contains no text files.
) else (
   echo ********This directory contains the following pdf files********
   echo.
   dir /b *.pdf
   )
if not exist *.xlsx (
echo This directory contains no text files.
) else (
   echo ********This directory contains the following xlsx files********
   echo.
   dir /b *.xlsx
   )
if not exist *.pptx (
echo This directory contains no text files.
) else (
   echo ********This directory contains the following pptx files********
   echo.
   dir /b *.pptx
   )
if not exist *.vsdx (
echo This directory contains no text files.
) else (
   echo ********This directory contains the following vsdx files********
   echo.
   dir /b *.vsdx
   )
if not exist *.docx (
echo This directory contains no text files.
) else (
   echo ********This directory contains the following docx files********
   echo.
   dir /b *.docx
   )
if not exist *.mp4 (
echo This directory contains no text files.
) else (
   echo ********This directory contains the following mp4 files********
   echo.
   dir /b *.mp4
   )
if not exist *.bat (
echo This directory contains no text files.
) else (
   echo ********This directory contains the following bat files********
   echo.
   dir /b *.bat
   )
if not exist *.txt (
echo This directory contains no text files.
) else (
   echo ********This directory contains the following text files********
   echo.
   dir /b *.txt
   )

run.bat

start test.bat
第一种方式运行结果
第二种方式运行结果(推荐)
Windows批处理脚本实现的两种方式运行结果

4、总结

        在实际的学习和工作中,如果不是特别依赖于某种编程语言,那么用户可以根据实际需求选择适合自己的方法来实现,利用编程语言也可以调用cmd或Process进行批处理操作。总的来说,有时编程语言甚至不如cmd命令或者batch批处理脚本更为直接有效,因此掌握基本的批处理命令可有效提高工作效率,下面是一些基本常用的cmd命令,记得多用help哦!!!

python test.py args1 args2 # 运行python代码
java -jar test.jar args1 args2 # 运行java代码
wget httpurl_file # 利用wget和url下载文件
start calc.exe # 打开计算器
start notepad.exe # 打开记事本
start explorer.exe # 打开文件资源管理器
help # 查看命令帮助
systeminfo # 查看系统信息
ipconfig # 显示、修改TCP/IP设置
hostname
echo %COMPUtERNAME% # 列出主机名称
rename # 重命名文件
move # 移动文件
copy # 赋值文件
xcopy # 复制文件和目录,包括子目录
del # 删除文件
F: # 进入F盘
cd test # 进入文件夹
dir # 查看目录文件
title # 为cmd窗口创建标题
color 48 # 窗口中的前景色和背景色
date /t # 显示当前系统日期
time # 显示当前系统时间
ping # 主要 TCP/IP 命令,测试网络连通性
PowerShell.exe 利用cmd进入或退出PowerShell
call xxx.bat args1 args2 # 调用xxx.bat并传参
regedit # 打开注册表编辑器
exit # 退出,关闭窗口

猜你喜欢

转载自blog.csdn.net/jing_zhong/article/details/124715349