2

I have a little script that will format a log file with all failed logins for users on the system. I have written the script to output the data in a text file in this format (two columns with the number of failed login attempts in the first, and the user in the second):

1,325 Unknown  
505 root   
17 adm  
16 ftp  
etc...  

I need this file formatted in HTML output on the console in this way (each line in the file be printed on a html line break):

<html>
<body><h1>Failed Login Attempts</h1> 
<br />1,325 Unknown 
<br />505 Root 
<br />17 adm 
etc....
</body>
</html>

What I currently do is save the file into a variable, and put that variable into the html like so:

file=$(cat finalo) #file name is finalo
#print to console
echo "
<html>
<body><h1>Failed Login Re...</h1>
<br />$file
</body>
</html>"

The output display's the entire file contents on one html <br />. My question is how can I get each line in the file to print on each <br />?

I have tried reading each specific line of the file, saving that into a variable, and then using that variable on each <br /> line like so:

line1=$(sed -n '1p' < finalo)
line2=$(sed -n '2p' < finalo)
line3=$(sed -n '3p' < finalo)

And:

<html>
<body><h1>Failed Login Report</h1>
<br />$line1
<br />$line2
<br />$line3
etc...

This solution gives me the correct output, however, aside from this solution being messy, a major flaw exists if the file has a different amount of lines than the ones hard coded, it will not display.

Any help would be appreciated! This is homework btw.

2

It's easier than you think:

echo "
<html>
<body><h1>Failed Login Attempts</h1>"

# The following line prepends <br /> before each line in finalo
sed 's|^|<br />|' finalo

echo "
</body>
</html>"
  • Wow, that was easy. That single line of code fixed all my problems! Thank you! – Sharrison Sep 15 '17 at 22:12
1

You can use also a while

#!/bin/bash
echo "
<html>
<body><h1>Failed Login Attempt</h1>"
while read line
do
    echo "<br />$line"
done < file
echo "</body>
</html>"

Or with a function

function r_lines()
{
    while read line
    do
        echo "<br />$line"
    done < file
    return $line
}

echo "
<html>
<body><h1>Failed Login Attempts</h1>
$(r_lines)
</body>
</html>"
  • These too solutions also worked! I do like the function solution. Having a Java programing background, I was always taught to separate functionality from logic. Thanks! – Sharrison Sep 15 '17 at 22:15

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.