如何为传递给 bash 循环的每个文件创建一个输出文件? [英] How to create one output file for each file passed to a loop in bash?

查看:37
本文介绍了如何为传递给 bash 循环的每个文件创建一个输出文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文件,我将它传递给一个 bash 命令,该命令将在循环中创建一个输出,如下所示:

I have a file that I pass to a bash command that will create an output in a loop like so:

for file in /file/list/*
do
    command
done

我希望将每个循环的标准输出保存到我​​的工作目录中的文本文件中.目前我正在尝试这个:

I wish to save the output that would have gone to standard out of each loop to a text file in my working directory. Currently I am trying this:

for file in /file/list/*
do
    command | tee "$file_command output.txt"
done

我希望看到的是在我当前目录中创建的名为 file1.txt_commandoutput.txt、file2.txt_commandoutput.txt 等的新文件.命令的输出应保存为每个文件的不同文件.但是我只创建了一个文件,它被称为.txt",并且无法被 Mac 上的任何标准软件打开.我是 bash 脚本的新手,因此非常感谢您的帮助!

What I expect to see are new files created in my current directory titled file1.txt_commandoutput.txt, file2.txt_commandoutput.txt, etc. The output of the command should be saved as a different file for each file. However I get only one file created and it's called ".txt" and can't be opened by any standard software on Mac. I am new to bash scripting, so help would be much appreciated!

谢谢.

推荐答案

您的脚本中有两个问题.

You have two issues in your script.

首先,错误的参数/变量被扩展(file_command 而不是 file),因为它后面跟着一个可以解释为名称一部分的字符(下划线, _).要修复它,将参数名称括在大括号中,如下所示:${file}_command(参见 Shell 参数扩展.

First, the wrong parameter/variable is expanded (file_command instead of file) because it's followed by a character that can be interpreted as part of the name (the underscore, _). To fix it, enclose the parameter name in braces, like this: ${file}_command (see Shell Parameter Expansion in bash manual).

第二,即使使用固定的变量名扩展,文件也不会在您的工作目录中创建,因为 file 包含一个绝对路径名 (/file/list/name).要修复它,您必须从路径名中剥离目录.您可以使用 basename 命令来做到这一点,或者更好地使用修改后的 shell 参数扩展来去除最长的匹配前缀,如下所示:${file##*/}(再次参见 Shell 参数扩展, 部分关于 ${parameter##word}).

Second, even with fixed variable name expansion, the file won't be created in your working directory, because the file holds an absolute pathname (/file/list/name). To fix it, you'll have to strip the directory from the pathname. You can do that with either basename command, or even better with a modified shell parameter expansion that will strip the longest matching prefix, like this: ${file##*/} (again, see Shell Parameter Expansion, section on ${parameter##word}).

全部放在一起,您的脚本现在看起来像:

All put together, your script now looks like:

#!/bin/bash
for file in /file/list/*
do
    command | tee "${file##*/}_command output.txt"
done

此外,只需将命令输出保存到文件中,而无需在终端中打印,您可以使用简单的 重定向,而不是tee,像这样:command >"${file##*/}_com...".

Also, to just save the command output to a file, without printing it in terminal, you can use a simple redirection, instead of tee, like this: command > "${file##*/}_com...".

这篇关于如何为传递给 bash 循环的每个文件创建一个输出文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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