简体   繁体   English

如何从Shell脚本创建批处理文件

[英]How to create a batch file from shell script

I have a script to run on a unix box that looks for the most recently-added file in a directory and writes the name of that file to a new file. 我有一个在unix框上运行的脚本,该框用于查找目录中最近添加的文件,并将该文件的名称写入新文件。 It looks like 看起来像

ls -t|head -n 1 >> ../latestfile.txt

However I now need to get this to run on a windows box and have been told it needs to be .bat. 但是我现在需要让它在Windows框上运行,并被告知它必须是.bat。 Can anyone help with what this would look like? 有人可以帮忙吗?

Your best bet is to install Cygwin and call it a day. 最好的选择是安装Cygwin并每天调用它。

Cygwin is a large collection of GNU and Open Source tools which provide functionality similar to a Linux distribution on Windows. Cygwin是GNU和开放源代码工具的大集合,它们提供的功能类似于Windows上的Linux发行版。

Afterwards you should the be able to run that command from the regular Windows command line, a Batch File, or a Scheduled Task. 之后,您应该能够从常规Windows命令行,批处理文件或计划任务中运行该命令。

This effectively gives the same result. 这有效地给出了相同的结果。

@echo off
 :latest file
for /f "delims=" %%a in ('dir /b /od /a-d') do >"latestfile.txt" echo %%a

An equivalent for ls -t in Windows cmd could be: Windows cmd ls -t的等效项可能是:

  • dir /B /TC /OD /AD - sorted (see /OD ) by creation date & time (see /TC ); dir /B /TC /OD /AD按创建日期和时间排序(请参阅/OD )(请参阅/TC );
  • dir /B /TW /OD /AD - sorted (see /OD ) by last write date & time (see /TW ): the same if /T switch omitted at all. dir /B /TW /OD /AD按上次写入日期和时间排序(请参阅/OD )(请参阅/TW ):如果完全省略/T开关,则相同。

head -n 1 equivalent: to get the most recent file name (add /TC switch if desired), ie last item in dir /b output to a variable: head -n 1等效项:获取最新的文件名(如果需要,添加/TC开关),即dir /b最后一项输出到变量:

for /F "delims=" %G in ('dir /B /OD /A-D') do set "_lastfile=%~G"

Next .bat should work (note doubled % in the loop variable name %%G ) and add a line containing filename (incl. extension if present, no path) of the recently changed file from current directory to the ..\\latestfile.txt . 下一个.bat应该工作(请在循环变量名称%%G注意%的两倍),并在当前目录中添加一个包含文件名的行(包括扩展名,如果没有扩展名,则没有路径)到当前目录..\\latestfile.txt Here the ..\\ means parent folder of the current directory. ..\\表示当前目录的父文件夹

@echo OFF
setlocal EnableExtensions
set "_lastfile="                 empty the `_lastfile` variable
for /F "delims=" %%G in ('dir /B /OD /A-D') do set "_lastfile=%%~G"
>> ..\latestfile.txt echo(%_lastfile%

To add fully qualified file name, change the last line as follows: 要添加标准文件名,请如下更改最后一行:

>> ..\latestfile.txt echo(%CD%\%_lastfile%

Resources (required reading): 资源 (必读):

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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