我正在尝试从日志文件中的特定行中删除行结尾。目标是从匹配行中删除行结尾,然后将这些行附加到与删除行结束条件不匹配的上一行。
示例日志:
[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
示例输出:
#!/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
我不确定最好的方法是什么,我有一些努力用sed以条件方式删除行结尾。
在每条线上潜在循环可能是最好的方法吗?
这就是我提出的并且它有效,我只是认为会有更好的不那么复杂/不那么线性的方式。
{{1}}
答案 0 :(得分:2)
您可以使用awk:
awk '{if ($0 ~ /^\[/) {if (p) print p; p=$0} else p = p " " $0} END{print p}' file.log
[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