如何遍历目录中的文件并更改路径并将后缀添加到文件名 [英] How to loop over files in directory and change path and add suffix to filename

查看:132
本文介绍了如何遍历目录中的文件并更改路径并将后缀添加到文件名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要编写一个脚本以不同的参数启动程序,但是我是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 line
  • basename 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,请使用for filename in 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屋!

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