1

I am pretty new to UNIX.

I am trying to replace maxretry = * in the fail2ban config file with maxtretry = 3, so that every single packages has max. three retries until the ip is blocked.

I know that there tons of questions about sed, but I didn't find any which answered my question.

I know sed as the following:

sed -i 's/old-word/new-word/g' /etc/fail2ban/config.local

(I forgot the local config file Name)

sed is powerful, but I didn't understand it. It replaces strings with regex, but creating a regex is pretty hard for me.

I tried:

sed -i 's/"maxretry = *"/"maxretry = 3"/g' /etc/fail2ban/config.local

As I excepted nothing was changed.

Can someone help me to understand sed? Exspecially with a placeholder like * for any Kind of number/numbers.

2

You can do:

sed -Ei.bak 's/^([[:blank:]]*maxretry[[:blank:]]*=).*/\1 3/' /etc/fail2ban/config.local
  • ^([[:blank:]]*maxretry[[:blank:]]*=) matches any whitespaces (if any) at the start, then the string maxretry and then again any whitespace if present followed by = and put all of these in captured group 1 (we will refer it in the replacement pattern)

  • The rest is simply matched by .*

  • The replacement pattern, \1 3, sets the key from captured group, \1 and the we have used the value as 3.

This will set the maxretry value to 3.


Also the original file will be backup up as /etc/fail2ban/config.local.bak and the modified file will be /etc/fail2ban/config.local.

If you do not want the backup:

sed -Ei 's/^([[:blank:]]*maxretry[[:blank:]]*=).*/\1 3/' /etc/fail2ban/config.local
  • Thanks a lot. I'll use it this evening. One more question: "•The rest is simply matched by .*" -> the rest is the rest of the current line, isn't it? – Ismoh Jun 8 '16 at 8:06
  • @Ismoh That's right – heemayl Jun 8 '16 at 8:08
  • just another question: I tried the following: sed -Ei 's/^([[:blank:]]*port[[:blank:]]*=[[:blank:]]*ssh[[:blank:]]*).*/\1 port = 6354/' /etc/fail2ban/jail.local and the output is "port = ssh port = 6354". Can you help me again? I thought I got it. – Ismoh Jun 8 '16 at 17:36
  • \1 was not right. without \1 it works well. thanks anyways :) – Ismoh Jun 8 '16 at 18:30
  • @Ismoh Not sure what you meant by that but not that the solutions do vary for differing examples. So don't take it for granted that when one solution is working for one input, will make it working for any similar sort of inputs. So please be precise with the inputs you provide.. – heemayl Jun 9 '16 at 19:02

Your Answer

By clicking "Post Your Answer", you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.