我有一个文件,该文件包含以下内容:
10 tiny toes
tree
this is that tree
5 funny 0
文件末尾有空格。我想获取文件最后一行(具有字符)的行号。如何在SED中做到这一点?
答案 0 :(得分:2)
这很容易通过awk
awk 'NF{c=FNR}END{print c}' file
使用sed
更棘手。您可以使用=
运算符,但这会将行号打印为标准输出,而不是模式空间。因此,您无法操纵它。如果要使用sed,则必须将其通过管道传输到另一个或使用tail
:
sed -n '/^[[:blank:]]*$/!=' file | tail -1
答案 1 :(得分:0)
您可以使用以下伪代码:
Replace all spaces by empty string
Remove all <beginning_of_line><end_of_line> (the lines, only containing spaces, will be removed like this)
Count the number of remaining lines in your file
答案 2 :(得分:0)
很难计算sed中的行号。某些版本的sed为您提供=
运算符,但这不是标准的。您可以使用外部工具生成行号,然后执行以下操作:
nl -s ' ' -n ln -ba input | sed -n 's/^\(......\)...*/\1/p' | sed -n '$p'
但是如果您打算这样做,则最好使用awk。
答案 3 :(得分:0)
这可能对您有用(GNU sed):
function botReady() {
bot.sortReplies();
botReply('Hello');
}
对于所有包含非空格字符的行,请打印行号。通过管道将此输出传递给sed的第二次调用,并仅打印最后一行。
替代:
sed -n '/\S/=' file | sed -n '$p'