我在一个目录中有许多 TSV 文件,我想将文件名附加为每一行的额外列。 例如,我的数据如下所示。
之前
文件名: snapper_User_list.txt
Username group
user1 admin
user2 users
文件名: marlin_User_list.txt
Username group
root admin
sql admin
我的理想状态是拥有一个如下所示的文本文件。
之后
文件名: output.txt
user1 admin snapper
user 2 users snapper
root admin marlin
sql admin marlin
现在我需要在 MS Windows 中完成这个。
我有下面的脚本工作,虽然它仍然在我的输出中显示完整的文件名。
Rem Rename the files by just using the name before the underscore.
for /f "tokens=1* delims=_" %%i in ( 'dir *.txt /b' ) do (
rename %%i_%%j %%i.txt
)
Rem Combine the files.
FOR %%I IN (*.txt) DO (
FOR /f "tokens=*" %%a IN (%%I) DO (
echo %%a%TAB%%%I>>combined.txt
)
)
这是非常难看的代码。
谢谢。 (更新 - 更新我的代码)
最佳答案
我假设您指的是文件名中出现的下划线。
@echo off
setlocal
::The following defines a TAB character that is not preserved on StackOverflow
set "TAB= "
for %%F in (*.txt) do call :processFile "%%F"
exit /b
:processFile
set "name=%~1"
set name=%name:_=&rem %
for /f "usebackq delims=" %%a in (%1) do echo %%a%TAB%%name%>>combined.txt
神奇的命令是set name=%name:_=&rem %
。它通过在语句中注入(inject) REMark 命令来工作。假设当前名称是 part1_part2.txt
。搜索替换展开后,完整语句变为set name=part1&rem part2.txt
编辑 - 改进的答案
看着您编辑过的问题,我意识到有更好的方法。我应该考虑使用 FOR/F 解析名称 :-) 你已经完成了 90%!
@echo off
setlocal
::The following defines a TAB character that is not preserved on StackOverflow
set "TAB= "
for %%F in (*.txt) do (
for /f "delims=_" %%I in ("%%F") do (
for /f "usebackq delims=" %%a in ("%%F") do echo %%a%TAB%%%I>>combined.txt
)
)
关于batch-file - Windows 批处理 - 在每一行上将文本附加到 TSV 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12667748/