如何遍历目录中的文件并更改路径并向文件名添加后缀 [英] How to loop over files in directory and change path and add suffix to filename
问题描述
我需要编写一个脚本,用不同的参数启动我的程序,但我是 Bash 的新手.我开始我的程序:
I need to write a script that starts my program with different arguments, but I'm new to Bash. I start my program with:
./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 for
end for
所以我真的很困惑如何从第一个参数创建第二个参数,所以它看起来像 dataABCD_Log1.txt 并启动我的程序.
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.
推荐答案
首先要注意几点:当你使用 Data/data1.txt
作为参数时,它真的应该是 /Data/data1.txt
(带前导斜线)?另外,外循环应该只扫描 .txt 文件,还是/Data 中的所有文件?这是一个答案,假设只有 /Data/data1.txt
和 .txt 文件:
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
注意事项:
/Data/*.txt
扩展为/Data 中文本文件的路径(包括/Data/部分)$( ... )
运行一个 shell 命令并将其输出插入命令行中的那个点basename somepath .txt
输出 somepath 的基本部分,从末尾删除 .txt(例如/Data/file.txt
->file
)
/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
)
如果您需要使用 Data/file.txt
而不是 /Data/file.txt
运行 MyProgram,请使用 "${filename#/}"
删除前导斜杠.另一方面,如果你真的想扫描Data
而不是/Data
,只需使用作为Data/*.txt
中的文件名.
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
.
这篇关于如何遍历目录中的文件并更改路径并向文件名添加后缀的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!