【问题标题】:Loop through results of sed循环遍历 sed 的结果
【发布时间】:2018-08-09 04:00:27
【问题描述】:

我无法遍历 sed 返回的存储在变量中的行。

目前看起来有点像这样

lines=$(sed -rne '/'"$timestamplastupload"'/,/'"$timestampnow"'/ p' /var/log/test.log)

for line in "$lines"; do

        echo "This line is: $line"

done

但到目前为止,这还不起作用,循环一次运行一次,而 $line 变量的内容似乎是整个 $lines 变量,因此只打印一次,而不是逐行循环,前缀为“此行是:“

我缺少什么能够逐个循环遍历 sed 输出的每一行。 (最终我会逐行将匹配的行上传到 API)所以我需要单独的每一行,以便我可以根据需要处理它们。

根据要求,sed 的一些输出已针对安全性进行了调整

Wed Feb 28 22:33:11 2018 us=452112 xxx/1.2.3.4:55487 [xxx] Inactivity timeout (--ping-restart), restarting
Wed Feb 28 22:33:11 2018 us=452112 xxx/1.2.3.4:55487 [xxx] Inactivity timeout (--ping-restart), restarting
Wed Feb 28 22:33:11 2018 us=452112 xxx/1.2.3.4:55487 [xxx] Inactivity timeout (--ping-restart), restarting
Wed Feb 28 22:33:11 2018 us=452180 xxx/1.2.3.4:55487 SIGUSR1[soft,ping-restart] received, client-instance restarting
Wed Feb 28 22:33:11 2018 us=452180 xxx/1.2.3.4:55487 SIGUSR1[soft,ping-restart] received, client-instance restarting
Wed Feb 28 22:33:11 2018 us=452180 xxx/1.2.3.4:55487 SIGUSR1[soft,ping-restart] received, client-instance restarting
Wed Feb 28 22:33:11 2018 us=452180 xxx/1.2.3.4:55487 SIGUSR1[soft,ping-restart] received, client-instance restarting

【问题讨论】:

标签: bash loops sed


【解决方案1】:

您的 sed 的输出会很有用(因为要处理 endlines),但除此之外,this question 似乎提供了一个符合这些思路的答案:

IFS=' ' read -r -a array <<< "$lines"
for element in "${array[@]}"
do
    echo "$element"
done

【讨论】:

  • 我开始认为这可能是回车等的情况,但我不知道如何确定是否是这种情况。尝试您的方法后,出现空格分割。
【解决方案2】:

请勿使用for 阅读。改用进程替换:

while read -r line; do
  # your logic
done < <(sed -rne '/'"$timestamplastupload"'/,/'"$timestampnow"'/ p' /var/log/test.log)

见:

【讨论】:

    猜你喜欢
    • 2013-09-14
    • 2019-02-18
    • 1970-01-01
    • 2015-10-05
    • 1970-01-01
    • 2016-06-07
    • 1970-01-01
    • 2021-09-06
    • 2011-01-03
    相关资源
    最近更新 更多