awk and sed questions
i have a mrtg config file that i am trying to replace some strings in. the format of the lines in question are like this
Title[3560-1_10127]: Traffic Analysis for 10127 -- 3560-1 where the 2nd instance on the line of 10127 needs replaced with the string "Port 27". thats easy to do with sed but what i want to do is to do that for all the ports incrementing my way through the file. in other words, there are lines that say 10101 through 10148 and i want to replace the 2nd instance on the line of 10101 with "Port 1" and then go onto the line with 10102 and replace its 2nd instance with "Port 2" this is breaking my brain. any of you have any ideas? thanks |
Hi,
do you mean something like this? Code:
sed -nr 's/(Title\[.*_([0-9]{3}([0-9]{2})).*)\2/\1Port \3/p' file |
Here's a gawk program that works for your sample:
Code:
$ cat rock1961.gawk Code:
$ cat rock1961.txt
|
In GNU awk the gensub function can replace the Nth occurrence of a matching pattern:
Code:
awk '{$0=gensub(/101([0-9][0-9])/,"Port \\1",2)}1' file Code:
awk '{port=gensub(/.*101([0-9][0-9]).*/,"\\1","g");print gensub(/101([0-9][0-9])/,("Port " port+0),2)}' |
You might want to consider always using at least the maximum number of digits required for the largest port number, with leading zeros. This makes the listing sort well, since the alphabetic form and the numeric form sort the same. Might not apply to your situation, but if it does, now is the time to get it right.
--- rod. Edit: wouldn't you know someone would say the same thing while I was typing. Note to self: learn to type fasterer. |
sed can also replace the nth instance on a line.
Code:
sed -i -r 's/101([0-4][0-9])/Port \1/2' file So you'd probably have to embed it in a shell loop instead to match each number in turn, and fool with zero-padding as well. bash v.4's zero-padding in brace-expansion makes it relatively easy. Code:
for num in {01..48}; do |
Also if you know the format is always the same:
Code:
awk '$5 = "Port " int(substr($5,4))' file |
Solved Awk question
Quote:
|
All times are GMT -5. The time now is 01:59 PM. |