【问题标题】:Print the middle line of any file UNIX打印任意文件的中间行 UNIX
【发布时间】:2014-11-13 02:34:07
【问题描述】:

我必须在没有 sed 和 awk 的情况下打印任何文本文件的中间行。

例如下面的file.txt:

line 1
line 2
line 3
line 4
line 5

我需要类似的东西:

$ command -flags file.txt
line 3

有什么命令吗?

谢谢。

【问题讨论】:

    标签: file unix text printing line


    【解决方案1】:

    不是最有效的,但可以在 bash 中使用。

    使用wc -l 计算行数,然后除以二。然后使用tail -n +N | head -n 1 仅打印Nth 行(其中N 从1 开始)。

    $ cat input.txt
    A
    B
    C
    D
    E
    $ tail -n +$(((`cat input.txt | wc -l` / 2) + 1)) input.txt | head -n 1
    C
    

    请注意,偶数行的文件没有单一的“中间行”。

    cat-ed 文件到wc -l,所以它不会打印文件名。

    【讨论】:

    • cat input.txt | wc -l 可以替换为wc -l < input.txt
    【解决方案2】:
    sed -n $(((`cat input.txt| wc -l`/ 2) + 1))p input.txt
    

    【讨论】:

    • 问题是没有sedawk怎么办?
    猜你喜欢
    • 2014-08-04
    • 2011-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-09
    • 2015-10-28
    • 1970-01-01
    相关资源
    最近更新 更多