【发布时间】:2016-01-08 19:03:18
【问题描述】:
我有一个函数应该获取特定行号之间的行,将其传递给它并存储在一个变量中,以及模式为“endhelp”的下一行
我现在的代码:
START_LINE=$1 #-- On which line the help is and where the search should start
#-- Where the help command block ends
END_LINE[1]=$(sed -n "$START_LINE,/endhelp/p=" filename)
#-- Add one number to END_LINE as a second array value to speed line extracting
END_LINE[2]=$((${END_LINE[1]}+1))
#-- The actual line extraction that outputs the whole lines
sed -n "$START_LINE,${END_LINE[1]}p; ${END_LINE[2]}q" filename
所以如果我有这样的东西:(注意:输入文件中还有其他类似的块,所以这就是起始行很重要的原因)
-- some text --
help
text and some more text
more words and text
third help thing line
stuff
hi
endhelp
-- some other text --
输出将是:
text and some more text
more words and text
third help thing line
stuff
hi
上面的代码可以工作吗?可以更有效地完成吗?还有当它检测到只有字符串'endhelp'的空行时如何让它停止?
更新
下面是更新后的代码,可以满足我的要求:
START_LINE=$2 #-- Where the help command block starts
awk 'BEGIN {OUTPUT=0} NR=='$START_LINE' {OUTPUT=1} /^endhelp$/ {exit} OUTPUT'
如果only 行有字符串'endhelp',它会停止并从$START_LINE 开始打印。我添加了BEGIN {OUTPUT=0},否则它会在某些旧设备上出错。
更新2
我再次编辑了代码,以修复它在到达“START_LINE”之前在空行上看到“endhelp”时退出的问题:
awk 'NR>='$START_LINE' {if ($0 ~ /^endhelp$/) {exit} else {$1=$1; print}}'
它更小,速度更快。它还添加了$1=$1,它从当前行中删除了尾随和前导空格。如果不需要,可以将其安全移除。
【问题讨论】:
-
你传递给脚本的是哪一行?
-
“帮助”所在的行,所以它会从那里开始打印