我正在编写一个csh脚本,它将从文件xyz中提取一行。 xyz文件包含否。代码行和我感兴趣的行出现在文件的2-3行之后。 我尝试了以下代码
set product1 = `grep -e '<product_version_info.*/>' xyz`
我希望它在某种程度上,以便当脚本找到该行时,它应该将该行保存在某个变量中作为字符串&amp;终止立即读取文件即。它不应该进一步读取提取线。
请帮助!!
答案 0 :(得分:2)
grep有一个-m
或--max-count
标志,告诉它在指定数量的匹配后停止。希望你的grep版本支持它。
set product1 = `grep -m 1 -e '<product_version_info.*/>' xyz`
从上面链接的手册页:
-m NUM, - max-count = NUM
Stop reading a file after NUM matching lines. If the input is standard input from a regular file, and NUM matching lines are output, grep ensures that the standard input is positioned to just after the last matching line before exiting, regardless of the presence of trailing context lines. This enables a calling process to resume a search. When grep stops after NUM matching lines, it outputs any trailing context lines. When the -c or --count option is also used, grep does not output a count greater than NUM. When the -v or --invert-match option is also used, grep stops after outputting NUM non-matching lines.
作为替代方案,您可以随时使用以下命令检查前几行(因为它始终出现在前2-3行):
set product1 = `head -3 xyz | grep -e '<product_version_info.*/>'`
答案 1 :(得分:0)
我想你要求返回文件中的第一个匹配行。如果是这样,一种解决方案是将grep
结果传递给head
set product1 = `grep -e '<product_version_info.*/>' xyz | head -1`