Search code examples
windowsbatch-filescriptingwindows-scripting

cmd - export 1 file name to txt


I'm new to scripting so this might be an easy one.

How may I export the name of ONE file in a directory to a text file ? I'm aware dir > text_file.txt will output the list of all files in the directory, however I need this to create a loop which will print every file name individually.

Thanks in advance.


Solution

  • Slightly vague answer for a slightly vague question.

    for /r %%G in (*) do echo %%G
    

    to get just, lets say .txt files, use:

    for /r %%G in (*.txt) do echo %%G
    

    nicer format if you wish to add more commands:

    for /r %%G in (*) do (
        echo Full path : %%G
        echo Name/Ext  : %%~nxG
    )
    

    EDIT:

    Heres a way to do what you mentioned in the comment, echo all files in current directory to a text file:

    rem first delete existing output files to clear them.
    del full_path.txt >nul
    del name_and_ext.txt >nul
    
    for /r %%G in (*) do (
        echo %%G >> full_path.txt
        echo %%~nxG >> name_and_ext.txt
    )
    

    Edit this however you please.

    Do note;

    rem this will override all content in file.txt with !variable!
    echo !variable! > file.txt
    
    rem this will add the content of !variable! to new lines accordingly
    echo !variable! >> file.txt