如何在目录中的文件遍历使用bash? [英] How to iterate over files in directory with bash?

查看:123
本文介绍了如何在目录中的文件遍历使用bash?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要编写不同的参数启动我的程序的脚本,但我是新来的抨击。我开始我的计划是这样的: ./ MyProgram.exe数据/ DATA1.TXT [日志/ data1_Log.txt] 。这里是伪code什么我想要做的:

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

所以我真的很困惑如何创建从第一个第二个参数,所以它看起来像dataABCD_Log1.txt,开始我的计划。帮助是非常AP preciated。附:我知道有simililar问题摆在那里,但我没有发现任何关于创建我的日志文件名。

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.

推荐答案

一对夫妇的注意事项第一:当您使用数据/ DATA1.TXT 作为一个参数,它应该真正做到 /Data/data1.txt ?此外,应外环仅扫描.txt文件或/数据的所有文件?这里有一个答案,假设 /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? 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

注:


  • /数据/ *。TXT 扩展到文本文件在/数据路径(的包括的中/数据/部分)

  • $(...)运行shell命令并在命令行中该点
  • 插入其输出
  • 基本名称somepath .TXT 输出somepath的底座部分,以txt从最终删除(如 /Data/file.txt - > 文件

  • /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 line
  • basename somepath .txt outputs the base part of somepath, with .txt removed from the end (e.g. /Data/file.txt -> file)

如果您需要与数据/ file.txt的而不是 /Data/file.txt 运行MyProgram,使用$ {#名/}删除前导斜线。在另一方面,如果它真的数据不是 /数据要扫描,只需使用 在数据/文件名*。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.

这篇关于如何在目录中的文件遍历使用bash?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆