我有一堆.txt文件,我希望将特定列(从所有这些文件中)复制到一个.txt文件中。需要创建output.txt文件
例如
file1.txt
a b c
j k l
file2.txt
d e f
m n o
file3.txt
g h i
p q r
output.txt
b e h
k n q
对于同样的我在Windows中寻找一个可以帮助我实现这一目标的批处理文件。任何形式的帮助将非常感激 :)。我只是批处理脚本的新手,因此如果这听起来是一个非常基本的问题,请原谅我。
答案 0 :(得分:1)
这可能不是您正在寻找的答案,但在批处理文件中处理字符串时,我遇到了类似但不完全正确的问题。我变得非常沮丧,我最终学习并使用python。
在Python中,这很简单:
for i in range(1,4):
f='c:\\file'+str(i)+'.txt' # Creates a variable for file1.txt, file2.txt formatted as c:\file1.txt. Path can be changed as needed.
f = open(f) # Opens the file
string=f.read() # Adds the contents of the file to a string
print(string.split('\t')[1]+'\t'+string.split('\t')[4]) # splits the string by tabs, and returns the 2nd and 5th item.
这会将其打印到屏幕上,从此处将其写入文件是微不足道的。
答案 1 :(得分:1)
此批处理解决方案将从文件夹中每个文件的所有行中获取第二个字符,并将它们输出到output.txt
,哇哇哇! :)
for %%a in (file*.txt) do (
for /f "tokens=2 delims= " %%b in (%%a) do echo %%b >>output.txt
)
让他们排队会更加困难,是非常必要的,还是他们可以在一个列表中,每行一个字符?
答案 2 :(得分:0)
编辑:不同的方式这样做(可能更直接),这个有另一个限制 - 可用变量/ env的大小。空间(对于XP大约为32kB,不限于Vista向上 - 至少每个MS文档)。它会创建一个类型的数组变量来保存转置行,然后输出它们:
@echo off
setlocal enabledelayedexpansion
set "tab= "
for %%F in (file*.txt) do (
set /a count=0
for /f "tokens=2 delims=%tab%" %%L in (%%F) do (
set /a count+=1
for /L %%T in (!count!,1,!count!) do (
set L[!count!]=!L[%%T]!%%L%tab%
)
)
)
for /L %%L in (1,1,%count%) do echo !L[%%L]!
首先,我要说batch
并不是最适合这项任务的(这在C
中可能是微不足道的),但如果你必须使用它,这是一种方式:
@echo off
setlocal enabledelayedexpansion
set "tab= "
for /f %%C in ('dir /b file*.txt') do set /a count+=1
(for %%F in (file*.txt) do (
set line=0
for /f "tokens=2 delims=%tab%" %%V in (%%F) do (
set "outline=%%F"
for /l %%N in (1,1,!line!) do (set "outline=%tab%!outline!")
set outline=!outline!%tab%%%V
set /a line+=1
echo !outline!
)
)) >presorted.txt
set /a cutoff=%count%-1
set line=0
for /f "tokens=2 delims=%tab%" %%O in ('sort /r presorted.txt') do (
set outp=%%O%tab%!outp!
set /a lc=!line!^%%count%
if !lc!==%cutoff% (
echo !outp!
set "outp="
)
set /a line+=1
)
工作原理:
for
和count
变量)()
分隔的第二个块)sort /r presorted.txt
)modulo count
将行块转换为列以开始新行(最后for
块)注意:
"tab= "
(第3行)必须包含实际标签tab
在任何可打印字符之前排序)。 !
个字符(当延迟扩展打开时需要特殊处理)。mybatchfile.bat >output.txt