【问题标题】:Read variable line by line in shell (dash included)在 shell 中逐行读取变量(包括破折号)
【发布时间】:2019-08-14 15:37:10
【问题描述】:

我有一个存储日志的变量。我想要的是读取包含日志的变量的每一行并保留该行或删除一些过滤内容。

问题是我的代码在 bash 上工作,但在破折号上不工作。

这是我的代码:

filtered_logs=""
while IFS= read -r line
do
 ...(store line to $filterered_logs if it comes throught filter )
done <<< "$logs"
logs="$filtered_logs"

此代码在 bash 中运行。但是 ' done ' 在 dash 中不起作用(因为 sh 在 ubuntu 中是默认的)。这是我的功课,我需要它适用于所有可能的外壳。

我尝试的是:

filtered_logs=""
echo "$logs" |
while IFS= read -r line
do
 ...(store line to $filterered_logs if it comes throught filter )
done
logs="$filtered_logs"

但是,如果我从 while 循环到 $filtered_logs 中存储一些东西,它就不起作用。而且我在使用调试器循环时也无法访问它。 (我认为整个 while 循环是一个全新的过程,因为我使用 | 运行它。

我的问题是如何使它工作,拜托。谢谢

【问题讨论】:

  • man echo ; man cat ;谷歌“shell输入重定向”
  • 每一个可能的 shell 似乎都是一个无限的任务。您是否需要使用 while 构造,或者您可以切换到awksed 或其他避免while 的工具(当它不是以换行符结尾时会出现更多问题,例如性能和跳过最后一行)?
  • 是的,我可以同时使用 awk 和 sed。而且好像其他同学也用过。遗憾的是我没有学会如何使用它,所以我以这个结束。

标签: shell sh


【解决方案1】:

在您的情况下使用干净的 posix api 很容易:

logs=$(
   printf "%s" "$logs" |
   while IFS= read -r line
   do
      echo "store this to logs"
   done
)

【讨论】:

  • printf "%s" "$(echo "$logs" | tail -3)" 将显示缺少最后一个换行符。
  • 非常感谢,它有效!是的,最后一行不见了。我将换行符附加到变量作为解决方法。你知道更好的解决方案吗?
猜你喜欢
  • 2016-05-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-28
  • 2022-07-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多