【问题标题】:Reading the second (or subsequent) line in Korn Shell读取 Korn Shell 中的第二行(或后续行)
【发布时间】:2022-01-08 06:52:18
【问题描述】:

我的操作系统是 AIX (7200-05-03-2136),我的 Korn Shell 版本是 ksh88(版本 M-11/16/88f),但我认为我的问题与版本无关。

考虑一个命令的单行输出。我可以通过“读取”轻松地将其放入变量中:

command | read variable

现在,假设该命令将有两行输出。有没有办法只将第二行捕获到变量中?使用一些外部程序很容易,例如:

command | sed '1d' | read variable

但我想避免这种情况并找到一个纯 shell 解决方案。我尝试了以下变体:

    command | { read -r junk ; read -r variable }
    command | { IFS=\n read junk ; read variable }
    command | IFS='\n' read junk variable

但所有这些都行不通。

【问题讨论】:

  • 命令 | tail -1 相当于 command | sed '1d'。我的问题的重点实际上是这是否可以在 shell 中完成,而不是使用外部命令。
  • 定义“不起作用”。会发生什么,这与您的预期有何不同?
  • command | { read -r variable; read -r variable; }
  • 假设需求可能发生变化(例如,这次是第 2 行,下次是第 1 行等),使用 while read -r x; do ...; done < <(command) 循环和计数器;当计数器达到所需的行号时,您将值存储在 variablebreak
  • "won't work" 显然意味着变量不会填充我希望填充的内容,在这种情况下是“命令”输出的第二行。我认为从问题的上下文来看这很明显。

标签: ksh


【解决方案1】:

首先将所有内容分配给一个变量。接下来您可以打印或分配第二行。

variable=$(echo "line 1
line 2")
echo "${variable#*$'\n'}"
# or
variable="${variable#*$'\n'}"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-02
    • 1970-01-01
    相关资源
    最近更新 更多