get the second last line from shell pipeline

2019-08-24 17:06发布

I want to get the second last line from the ls -l output. I know that ls -l|tail -n 2| head -n 1 can do this, just wondering if sed can do this in just one command?

标签: shell
4条回答
冷血范
2楼-- · 2019-08-24 17:35

Try this to delete second-last line in file

sed -e '$!{h;d;}' -e x filename
查看更多
▲ chillily
3楼-- · 2019-08-24 17:36
ls -l|sed -n 'x;$p'

It can't do third to last though, because sed only has 1 hold space, so can only remember one older line. And since it processes the lines one at a time, it does not know the line will be next to last when processing it. awk could return thrid to last, because you can have arbitrary number of variables there, but the script would be much longer than the tail -n X|head -n 1.

查看更多
欢心
4楼-- · 2019-08-24 17:42
tac filename | sed -n 2p

-- but involves a pipe, too

查看更多
Explosion°爆炸
5楼-- · 2019-08-24 17:52

In a awk one-liner :

echo -e "aaa\nbbb\nccc\nddd" | awk '{v[c++]=$0}END{print v[c-2]}'
ccc
查看更多
登录 后发表回答