Reputation: 33
I have a number of TSV files in a directory, and I would like to append the file name as an extra column on every line. For Example my data looks like the below.
BEFORE
FileName: snapper_User_list.txt
Username group
user1 admin
user2 users
FileName: marlin_User_list.txt
Username group
root admin
sql admin
My ideal state would to be have one text file that looks like the below.
AFTER
FileName: output.txt
user1 admin snapper
user 2 users snapper
root admin marlin
sql admin marlin
For now I need to complete this in MS Windows.
I have the below script working, although it still displays the full filename in my output.
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
)
)
It's pretty ugly code.
Thanks. (updated - update to my code)
Upvotes: 3
Views: 520
Reputation: 130919
I am going to assume you are referring to an underscore that occurs in the file name.
@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
The magic command is set name=%name:_=&rem %
. It works by injecting a REMark command into the statement. Assume the current name is part1_part2.txt
. After the search and replace expansion, the full statement becomes set name=part1&rem part2.txt
EDIT - Improved answer
Looking at your edited question, I realize there is a better way. I should have thought of parsing the name using FOR /F :-) You were 90% there!
@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
)
)
Upvotes: 2