从文件中检索特定值
Retreive specific values from file
我有一个文件 test.cf 包含:
process {
withName : teq {
file = "/path/to/teq-0.20.9.txt"
}
}
process {
withName : cad {
file = "/path/to/cad-4.0.txt"
}
}
process {
withName : sik {
file = "/path/to/sik-20.0.txt"
}
}
我想检索文件末尾关联的 teq、cad 和 sik 值
我首先想到的是
grep -E 'teq' test.cf
只获取第二个原始数据,然后删除行中的部分重复
但这样做可能更容易:
for a in test.cf
do
line=$(sed -n '{$a}p' test.cf)
if line=teq
#next line using sed -n?
do print nextline &> teq.txt
else if line=cad
do print nextline &> cad.txt
else if line=sik
do print nextline &> sik.txt
done
(显然不行)
编辑:
需要的输出:
teq.txt 包含 teq-0.20.9
,cad.txt 包含 cad-4.0
和 sik.txt 包含 sik-20.0
有什么好的方法吗?感谢您的意见
根据您给定的样本:
awk '/withName/{close(f); f= ".txt"}
/file/{sub(/.*\//, ""); sub(/\.txt".*/, "");
print > f}' ip.txt
/withName/{close(f); f= ".txt"}
如果行包含 withName
,使用第三个字段将文件名保存在 f
中。 close()
将关闭任何以前的文件句柄
/file/{sub(/.*\//, ""); sub(/\.txt".*/, "");
如果行包含 file
,删除除所需值之外的所有内容
print > f
打印修改后的行并重定向到 f
中的文件名
- 如果您可以有多个条目,请使用
>>
而不是 >
这是 awk 中的解决方案:
awk '/withName/{name=} /file =/{print > name ".txt"}' test.cf
/withName/{name=}
:当我看到包含“withName”的行时,我保存那个名字
- 当我看到带有“file =”的行时,我打印
我有一个文件 test.cf 包含:
process {
withName : teq {
file = "/path/to/teq-0.20.9.txt"
}
}
process {
withName : cad {
file = "/path/to/cad-4.0.txt"
}
}
process {
withName : sik {
file = "/path/to/sik-20.0.txt"
}
}
我想检索文件末尾关联的 teq、cad 和 sik 值
我首先想到的是
grep -E 'teq' test.cf
只获取第二个原始数据,然后删除行中的部分重复
但这样做可能更容易:
for a in test.cf
do
line=$(sed -n '{$a}p' test.cf)
if line=teq
#next line using sed -n?
do print nextline &> teq.txt
else if line=cad
do print nextline &> cad.txt
else if line=sik
do print nextline &> sik.txt
done
(显然不行)
编辑:
需要的输出:
teq.txt 包含 teq-0.20.9
,cad.txt 包含 cad-4.0
和 sik.txt 包含 sik-20.0
有什么好的方法吗?感谢您的意见
根据您给定的样本:
awk '/withName/{close(f); f= ".txt"}
/file/{sub(/.*\//, ""); sub(/\.txt".*/, "");
print > f}' ip.txt
/withName/{close(f); f= ".txt"}
如果行包含withName
,使用第三个字段将文件名保存在f
中。close()
将关闭任何以前的文件句柄/file/{sub(/.*\//, ""); sub(/\.txt".*/, "");
如果行包含file
,删除除所需值之外的所有内容print > f
打印修改后的行并重定向到f
中的文件名- 如果您可以有多个条目,请使用
>>
而不是>
- 如果您可以有多个条目,请使用
这是 awk 中的解决方案:
awk '/withName/{name=} /file =/{print > name ".txt"}' test.cf
/withName/{name=}
:当我看到包含“withName”的行时,我保存那个名字- 当我看到带有“file =”的行时,我打印