【发布时间】:2016-05-16 22:16:17
【问题描述】:
我正在尝试从日志文件中的特定行中删除行尾。目标是从匹配行中删除行尾,然后将这些行附加到与删除行尾条件不匹配的前一行。
示例日志:
[username] [object] [ip address] [datetime] [pid] :>MESSAGE TYPE:Message
[username] [object] [ip address] [datetime] [pid] :>MESSAGE TYPE:Message
[username] [object] [ip address] [datetime] [pid] :>MESSAGE TYPE:Message
[username] [object] [ip address] [datetime] [pid] :>MESSAGE TYPE:Message
Log Message Overflowing
Log Message Overflowing
Log Message Overflowing
Log Message Overflowing
[username] [object] [ip address] [datetime] [pid] :>MESSAGE TYPE:Message
[username] [object] [ip address] [datetime] [pid] :>MESSAGE TYPE:Message
[username] [object] [ip address] [datetime] [pid] :>MESSAGE TYPE:Message
[username] [object] [ip address] [datetime] [pid] :>MESSAGE TYPE:Message
[username] [object] [ip address] [datetime] [pid] :>MESSAGE TYPE:Message
Log Message Overflowing
Log Message Overflowing
Log Message Overflowing
[username] [object] [ip address] [datetime] [pid] :>MESSAGE TYPE:Message
[username] [object] [ip address] [datetime] [pid] :>MESSAGE TYPE:Message
示例输出:
[username] [object] [ip address] [datetime] [pid] :>MESSAGE TYPE:Message
[username] [object] [ip address] [datetime] [pid] :>MESSAGE TYPE:Message
[username] [object] [ip address] [datetime] [pid] :>MESSAGE TYPE:Message
[username] [object] [ip address] [datetime] [pid] :>MESSAGE TYPE:Message Log Message Overflowing Log Message Overflowing Log Message Overflowing Log Message Overflowing
[username] [object] [ip address] [datetime] [pid] :>MESSAGE TYPE:Message
[username] [object] [ip address] [datetime] [pid] :>MESSAGE TYPE:Message
[username] [object] [ip address] [datetime] [pid] :>MESSAGE TYPE:Message
[username] [object] [ip address] [datetime] [pid] :>MESSAGE TYPE:Message
[username] [object] [ip address] [datetime] [pid] :>MESSAGE TYPE:Message Log Message Overflowing Log Message Overflowing Log Message Overflowing
[username] [object] [ip address] [datetime] [pid] :>MESSAGE TYPE:Message
[username] [object] [ip address] [datetime] [pid] :>MESSAGE TYPE:Message
我不确定解决此问题的最佳方法是什么,并且我在使用 sed 有条件地删除行尾时遇到了一些困难。
可能循环遍历每一行可能是最好的方法?
这是我想出的,它有效,我只是认为会有更好的更简单/更线性的方式。
#!/bin/bash
PrevNoMatchLine=""
PrevMatchLine=""
while read -r line; do
if [[ $line =~ ^[^\[] ]]; then
PrevMatchLine+="$line "
else
if [[ $PrevMatchLine ]]; then
PrevNoMatchLine+=" $PrevMatchLine"
PrevMatchLine=""
echo $PrevNoMatchLine
else
PrevNoMatchLine=$line
fi
echo $line
fi
done < test.log
【问题讨论】: