Simple bash expression analysis in bash

I want to parse a log file (log.txt) that contains lines similar to the following:

2010-10-19 07:56:14 URL:http://www.website.com/page.php?ID=26 [13676] -> "www.website.com/page.php?ID=26" [1]
2010-10-19 07:56:14 URL:http://www.website.com/page.php?ID=44 [14152] -> "www.website.com/page.php?ID=44" [1]
2010-10-19 07:56:14 URL:http://www.website.com/page.php?ID=13 [13681] -> "www.website.com/page.php?ID=13" [1]
2010-10-19 07:56:14 ERROR:Something bad happened
2010-10-19 07:56:14 ERROR:Something really bad happened
2010-10-19 07:56:15 URL:http://www.website.com/page.php?ID=14 [12627] -> "www.website.com/page.php?ID=14" [1]
2010-10-19 07:56:14 ERROR:Page not found
2010-10-19 07:56:15 URL:http://www.website.com/page.php?ID=29 [13694] -> "www.website.com/page.php?ID=29" [1]

As you might have guessed:

1) I need to extract this part from each line:

2010-10-19 07:56:15 URL:http://www.website.com/page.php?ID=29 [13694] -> "www.website.com/page.php?ID=29" [1]
------------------------^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

2) This part goes to another file (log.html) as follows:

<a href="http://www.website.com/page.php?ID=29">http://www.website.com/page.php?ID=29</a>

I need to do this through a bash script that will run on the * nix platform. I have no idea about shell programming, so a detailed script will be highly appreciated, pointers to bash will make a link to programming.

+3
source share
5 answers

This should work:

sed -n 's%^.* URL:\(.*\) \[[0-9]*\] -> .*$%<a href="\1">\1</a>%p' log.txt
+2
source

Here is the bash solution

#!/bin/bash
exec 4<"log.txt"
while read -r line<&4
do
  case "$line" in
    *URL:* )
      url="${line#*URL:}"
      url=${url%% [*}
      echo "<a href=\"${url}\">${url}</a>"
  esac
done
exec 4<&-
+5
source

awk script, , .

awk '/URL:/ { sub(/^URL:/,"", $3); printf "<a href=\"%s"\">%s</a>\n", $3, $3; }'
+2

sed:

sed -n 's/.*URL:\([^ ]\+\) .*/<a href="\1">\1<\/a>/;/<a href/p' logfile

( : URL- , , , .)

+1
source

Something like that:

while read line
do
        URL=$(echo $line | egrep -o 'URL:[^ ]+' | sed  's/^URL://')     
        if [ -n "$URL" ]; then
                echo "<a href=\"$URL\">$URL</a>" >> output.txt
        fi  
done < input.txt
+1
source

Source: https://habr.com/ru/post/1770299/


All Articles