将回声输出列表保存到 .txt

Jor*_*ner 2 bash shell-script

我在尝试将一长串回声输出保存为桌面上的 .txt 文件时遇到了很多麻烦。我在优胜美地 10.10.4 中使用 Bash。我对 Bash 还是很陌生,所以感谢任何帮助和提示。

目标是打印每次脑部扫描使用的协议的名称,以获得一长串脑部扫描。我使用了一个 for 循环来递归地遍历每个脑部扫描,提取使用的协议,然后回显它以及用于获取该信息的确切文件的路径。

我的脚本:

for i in /Path/to/scans/
do

for file in "$i/"001*/0001.dcm
do

# If there is no such file here, just skip this scan.
if [ ! -f "$file" ]
then
echo "Skipping $i, no 0001.dcm file here" >&2
continue
fi

# Otherwise take the protocol data from scan out
line= dcmdump +P 0040,0254 0001.dcm 
## dcmdump is the command line tool needed to pull out this data. 
## In my case I am saving to variable "line" the protocol used in 
## the scan that this single 0001.dcm file belongs to (scans require 
## many .dcm files but each one contains this kind of meta-data).

# Print the result
echo "$line $file"

break
done
done
Run Code Online (Sandbox Code Playgroud)

所以这个脚本几乎可以工作。在我的终端窗口中,我确实得到了一长串使用的协议,以及用于每次扫描的 0001.dcm 文件的绝对文件路径。

我的问题是,当我将其更改为

echo "$line $file" >> /Users/me/Desktop/scanparametersoutput.txt
Run Code Online (Sandbox Code Playgroud)

出现在我桌面上的文本文件是空白的。任何人都知道我做错了什么?

rme*_*cer 6

您在脚本中遇到的一个问题是这一行:

line= dcmdump +P 0040,0254 0001.dcm
Run Code Online (Sandbox Code Playgroud)

它没有分配dcmdumpto的输出line,而是dcmdump使用名为lineset to的环境变量运行您的命令''。您可以在此处阅读更多相关信息。

因此,您实际看到的是dcmdump脚本运行的输出,而不是 的输出$line,因为$line没有分配任何内容。

要捕获程序的输出,请使用语法

line=$(dcmdump +P 0040,0254 0001.dcm)
Run Code Online (Sandbox Code Playgroud)

(另请注意,=为了安全起见,标志前后没有空格。)

$() 在子shell中运行括号内的代码,然后用该代码的输出“替换”自身。

您可能也希望0001.dcmdcmdump命令中$file使用它,但我不熟悉它,所以我将把它留给您。