[英]Print second last line from variable in bash
VAR="1\n2\n3"
I'm trying to print out the second last line. 我正在尝试打印出倒数第二行。 One liner in bash! 重击一班!
I've gotten so far: printf -- "$VAR" | head -2
到目前为止,我已经了解了: printf -- "$VAR" | head -2
printf -- "$VAR" | head -2
It however prints out too much. 但是,它打印太多。
I can do this with a file no problem: tail -2 ~/file | head -1
我可以用一个文件来做到这一点,没问题: tail -2 ~/file | head -1
tail -2 ~/file | head -1
You almost done this task by yourself. 您几乎自己完成了这项任务。 Try 尝试
VAR="1\n2\n3"; printf -- "$VAR"|tail -2|head -1
Here is one pure bash way of doing this: 这是执行此操作的一种纯bash方法:
readarray -t arr < <(printf -- "$VAR") && echo "${arr[-2]}"
2
You may also use this awk
as a single command: 您也可以将此awk
用作单个命令:
VAR="1\n2\n3"
awk -F '\\\\n' '{print $(NF-1)}' <<< "$VAR"
2
Use echo -e
for backslash interpretation and to translate \\n
to newlines and print the interested line number using NR
. 使用echo -e
进行反斜杠解释,并将\\n
转换为换行符,然后使用NR
打印感兴趣的行号。
$ echo -e "${VAR}" | awk 'NR==2'
2
With multiple lines and do, tail
and head
can be used to print any particular line number. 对于多行和多行,可以使用tail
和head
打印任何特定的行号。
$ echo -e "$VAR" | tail -2 | head -1
2
or do a fancy sed
, where you keep the previous line in the buffer-space ( x
) to print and keep deleting until the last line, 或执行sed
,将您的前一行保留在缓冲区( x
)中进行打印,并继续删除直到最后一行,
$ echo -e "$VAR" | sed 'x;$!d'
2
使用临时变量和扩展可能会更有效
var=$'1\n2\n3' ; tmpvar=${var%$'\n'*} ; echo "${tmpvar##*$'\n'}"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.