简体   繁体   中英

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

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

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:

readarray -t arr < <(printf -- "$VAR") && echo "${arr[-2]}"

2

You may also use this awk as a single command:

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 "${VAR}" | awk 'NR==2'
2

With multiple lines and do, tail and head can be used to print any particular line number.

$ 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,

$ echo -e "$VAR" | sed 'x;$!d'
2

使用临时变量和扩展可能会更有效

var=$'1\n2\n3' ; tmpvar=${var%$'\n'*} ; echo "${tmpvar##*$'\n'}"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM