1

While studying about fail2ban I came across this command. I never worked with awk before, only with sed. I don't understand why there are both printf and print, there:

awk '{ printf "# "; print; }' /etc/fail2ban/jail.conf | sudo tee /etc/fail2ban/jail.local

Why are both there?

BTW, if you know one, I invite you to share a sed version in the comments.

  • 1
    It's a clunkier way of writing '{printf "# %s\n", $0}'. – jasonwryan Jan 7 '18 at 5:47
  • And, therefore, the sed version would be sed 's/^/# /' /etc/fail2ban/jail.conf | sudo tee /etc/fail2ban/jail.local. – John1024 Jan 7 '18 at 5:50
5

The first printf is to append the character # to each line of the input file which in awk is represented by $0 and then the modified line (with # added before) is printed out to the console using the print clause.

You could just ignore one and run it on the command line to see which one does what.

seq 1 5 | awk '{ printf "# "; print; }'
# 1
# 2
# 3
# 4
# 5

It could perhaps be simply written with printf alone or just with print alone as

awk '{ printf "# %s\n" , $0  }'

You need the new-line character \n because printf does not print it by default.

awk '{ print "# "$0  }'
  • One thing I miss: If tee also prints in console (and into a file), why do we need print when tee is there?... – Arcticooling Jan 8 '18 at 0:15
  • You don't need tee(1), you need sudo(1) for the elevate permissions required to write under /etc. As written it's arguably safer than running awk(1) as root. (Additionally you can take the suggestion in this answer to test the command then append the privileged part after you're sure it works as intended.) – Matthew Gauthier Jan 8 '18 at 5:57
  • 1
    Alternatively awk '{ print "#", $0 }' with the default value of OFS. – Kusalananda Jul 19 '18 at 7:35

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.