如何解决grep文件中的值,然后将其用作文件夹名称以查找文件并进行打印
抱歉,标题令人困惑。我找不到更好的标题来描述这个问题。我正在使用gnuplot绘制一些文件。我尝试绘制的文件位于标题为process的文件夹中。在进程文件夹中是另一个名为100的文件夹;结构如下;
“ plot”是我使用gnuplot调用的文件。
文件图具有以下行;
file='file.dat'
time = "cat file | grep 'time' | cut -d' ' -f2 | tr -d ';' | awk 'NR==1{print $1}'"
plot \
"process/".time."/speed.txt" using 1:3 with line lt 2 lc 6 title ""
因此,目标是在file.dat中查找单词time并削减其值(在本例中为100),并将其用作我要绘制speed.txt文件的文件夹名称。但是,我执行gnuplot时似乎无法使用。有人可以帮忙吗?
非常感谢您!
解决方法
尽管gnuplot并非用于解析文件,但是您仍然可以做到这一点,有时还需要一些奇怪的解决方法。 当然,可以使用您提到的工具来实现此目的:cat,grep,cut,tr和awk。但是,并不是每个人都在使用Linux,并且手头有这些工具。因此,如果可能的话,虽然不是最佳选择,但我个人更喜欢具有独立于平台的“仅gnuplot”解决方案。
因此,以下代码的基本作用是逐行将文件.as-console-wrapper{min-height:100%;}
“绘制”到虚拟表中,并每次检查当前行是否包含字符串file.dat
。如果是,则将其余行写到变量time:
中。
获取有关以下命令的更多信息:myValue
,help strstrt
,help strlen
,help strcol
,help ternary
。
文件: help datafile separator
file.dat
代码:
### file.dat
This is a data file
which contains something
but also a line with
time:100
And many more things...
Maybe also some data...?
1 1.1
2 2.2
3 3.3
4 4.4
# end of file
结果:
### extract key&value from a file and use it in path
reset session
myFile = 'file.dat'
myKey = 'time:'
myValue = ''
myPath(s) = sprintf('process/%s/speed.txt',s)
getValue(line) = strstrt(line,myKey) > 0 ? myValue = line[strstrt(line,myKey)+strlen(myKey):] : myValue
# extract the value for key
set datafile separator "\n"
set table $Dummy
plot myFile u (getValue(strcol(1))) w table
unset table
set datafile separator whitespace
print myValue
print myPath(myValue)
# Your plot command would then look,e.g. like this:
plot myPath(myValue) using 1:3 with line lt 2 lc 6 title ""
### end of code
,
首先,要从gnuplot运行shell命令并以文本形式获取其标准输出,请使用system
函数。
filter_command = "cat ..."
time = system( filter_command )
第二,仅将其传递给system
时,您定义的命令字符串“ cat ...”将无法正常工作。您打算从gnuplot的file
变量中将cat file
中的字符串cat file.dat
扩展为file
。
为此,我们还需要一步。有两种方法可以做到这一点。
- 使用
.
运算符连接字符串
file='file.dat'
filter_command = "cat " . file . " | grep 'time' | cut -d' ' -f2 | tr -d ';' | awk 'NR==1{print $1}'"
- 使用
sprintf
函数
file='file.dat'
filter_template = "cat %s | grep 'time' | cut -d' ' -f2 | tr -d ';' | awk 'NR==1{print $1}'"
filter_command = sprintf(filter_template,file)
脚本
最终脚本如下所示。
file='file.dat'
filter_template = "cat %s | grep 'time' | cut -d' ' -f2 | tr -d ';' | awk 'NR==1{print $1}'"
filter_command = sprintf(filter_template,file)
time = system( filter_command )
plot "process/".time."/speed.txt" using 1:3 with line lt 2 lc 6 title ""
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。