如何用Bash迭代目录中的文件? [英] How to iterate over files in a directory with Bash?
问题描述
我需要编写一个以不同参数启动我的程序的脚本,但我是Bash的新手。我开始这样的程序:
$ b
下面是我想要做的伪代码: 所以我很困惑如何创建第二个参数第一个,所以它看起来像dataABCD_Log1.txt并启动我的程序。帮助非常感谢。 我知道这里有类似的问题,但是我没有发现创建我的日志文件的名字。 ./ MyProgram.exe Data / data1.txt [Logs / data1_Log.txt] $ c $
为每个文件名在/数据do
为int i = 0,i = 3,i ++
./MyProgram.exe数据/文件名.txt日志/文件名_Log {i} .txt
结束如果
结束为
Data / data1.txt
作为参数时,它应该真的是 /Data/data1.txt
领先的斜线)?此外,外环应该只扫描.txt文件还是扫描/ Data中的所有文件?这是一个答案,假设 /Data/data1.txt
和.txt文件:
#!/ bin / bash
作为/Data/*.txt中的文件名; ((i = 0; i <= 3; i ++))为
;
./MyProgram.exe$ filenameLogs / $(basename$ filename.txt)_Log $ i.txt
done
done
$ b $ ul
$ li $ $ $ / data / * .txt 展开到/ Data(包括 / Data / part)文本文件的路径
$(...)
运行一个shell命令,并在命令行中输入它的输出 basename somepath .txt
输出某个路径的基本部分,并从末尾删除.txt(例如 /Data/file.txt
- > file
)如果您需要使用<$ c $运行MyProgram c> data / file.txt 而不是 /Data/file.txt
,使用$ {filename#/}
删除前导斜杠。另一方面,如果您要扫描的是 Data
而不是 / Data
,只需使用用于Data / *。txt文件名
。
I need to write a script that starts my program with different arguments, but I'm new to Bash. I start my program like this:
./MyProgram.exe Data/data1.txt [Logs/data1_Log.txt]
.
Here is the pseudocode for what i want to do:
for each filename in /Data do
for int i = 0, i = 3, i++
./MyProgram.exe Data/filename.txt Logs/filename_Log{i}.txt
end if
end for
So I'm really puzzled how to create second argument from the first one, so it looks like dataABCD_Log1.txt and start my program. Help is very much appreciated.
P.S. I know there are simililar questions out there, but I found nothing on creating my logfile name.
A couple of notes first: when you use Data/data1.txt
as an argument, should it really be /Data/data1.txt
(with a leading slash)? Also, should the outer loop scan only for .txt files, or all files in /Data? Here's an answer, assuming /Data/data1.txt
and .txt files only:
#!/bin/bash
for filename in /Data/*.txt; do
for ((i=0; i<=3; i++)); do
./MyProgram.exe "$filename" "Logs/$(basename "$filename" .txt)_Log$i.txt"
done
done
Notes:
/Data/*.txt
expands to the paths of the text files in /Data (including the /Data/ part)$( ... )
runs a shell command and inserts its output at that point in the command linebasename somepath .txt
outputs the base part of somepath, with .txt removed from the end (e.g./Data/file.txt
->file
)
If you needed to run MyProgram with Data/file.txt
instead of /Data/file.txt
, use "${filename#/}"
to remove the leading slash. On the other hand, if it's really Data
not /Data
you want to scan, just use for filename in Data/*.txt
.
这篇关于如何用Bash迭代目录中的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!