awk - Remove N characters after matching string from Fortigate logfile - Stack Overflow

admin2025-04-17  2

Looking for a way to remove characters after the matching string

Example data:

srcip=10.1.100.11 srcport=58012 srcintf="port12" srcintfrole="undefined" dstip=23.59.154.35 dstport=80

Desired Output:

srcip=10.1.100.11 srcport= srcintf="port12" srcintfrole="undefined" dstip=23.59.154.35 dstport=80

Here I'm looking to remove the characters after srcport=' '. In this case it will always be 6 characters. But it would be nice to account for all characters after = until the space starts before srcintf.

There are quite a few examples of removing everything before or after the match, but can't find an example for what I'm looking for.

Looking for a way to remove characters after the matching string

Example data:

srcip=10.1.100.11 srcport=58012 srcintf="port12" srcintfrole="undefined" dstip=23.59.154.35 dstport=80

Desired Output:

srcip=10.1.100.11 srcport= srcintf="port12" srcintfrole="undefined" dstip=23.59.154.35 dstport=80

Here I'm looking to remove the characters after srcport=' '. In this case it will always be 6 characters. But it would be nice to account for all characters after = until the space starts before srcintf.

There are quite a few examples of removing everything before or after the match, but can't find an example for what I'm looking for.

Share edited Jan 31 at 15:56 Arnab Nandy 6,7425 gold badges47 silver badges51 bronze badges asked Jan 31 at 13:13 user29447110user29447110 2
  • Can you show what output you expect? It's not exactly clear from your description, unfortunately. – choroba Commented Jan 31 at 13:20
  • Output would be: srcip=10.1.100.11 srcport= srcintf="port12" srcintfrole="undefined" dstip=23.59.154.35 dstport=80 Where the data related to srcport then is removed – user29447110 Commented Jan 31 at 13:37
Add a comment  | 

2 Answers 2

Reset to default 4

Using gnu sed, match scrport= followed by digits and replace with srcport=:

$ sed 's/srcport=[[:digit:]]\+/srcport=/' file
srcip=10.1.100.11 srcport= srcintf="port12" srcintfrole="undefined" dstip=23.59.154.35 dstport=80

Remove N characters after matching string

GNU AWK allows you to use {n} Regexp Operator to express previous item repeated n times, therefore, for file.txt content being

srcip=10.1.100.11 srcport=58012 srcintf="port12" srcintfrole="undefined" dstip=23.59.154.35 dstport=80

command

awk '{sub(/srcport.{6}/,"srcport=");print}' file.txt

gives output

srcip=10.1.100.11 srcport= srcintf="port12" srcintfrole="undefined" dstip=23.59.154.35 dstport=80

Explanation: sub does substitution once, . denotes any character, {6} repeated 6 times, print does output altered line.

(tested in GNU Awk 5.3.1)

转载请注明原文地址:http://anycun.com/QandA/1744860793a88646.html