bash - 循环 sed 的结果

标签 bash loops sed

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

目前看起来有点像这样

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

for line in "$lines"; do

        echo "This line is: $line"

done

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

我缺少什么能够逐条循环遍历 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

最佳答案

不要使用for 来阅读。改为使用进程替换:

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

参见:

关于bash - 循环 sed 的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49043690/

相关文章:

linux - 将对目录中的所有文件执行程序的 Bash 脚本

c++ - while 循环、字符串和整数

c - 如何让我的代码免于进入无限循环?

bash - 如何使用 bash 从另一个 .txt 文件中的单词列表中删除文件中的单词?

linux - sed 命令编辑多个文件(插入,替换行)

python - 访问 URL 时打开 LED

bash - 删除 bash 中除最新的 X 文件之外的所有文件

mysql - 如何使用 ssh 从命令行执行 init 脚本

php - Break While 循环添加 "last"到 <div>

regex - sed OR regex 如何删除圆括号之间的所有内容