how to get all attribute name and value from HTML code using awk or sed

Viewed 148

Here is my file that has each line as mentioned below:

<a href="abc.com" aria-label="abc ofe" class="abc"><span class="bcd">abc</span><span class="icon"></span></a> 

here is expected output:

href="abc.com" 
aria-label="abc ofe" 
class="abc"
class="bcd"
class="icon"

Here is what I got:

awk '{for(i=1; i<=NF; ++i)printf "%s%s", $i, (i<NFi?FS:(i<NF?"\n":RS))}'

echo "<a href="abc.com" aria-label="abc ofe" class="abc"><span class="bcd">abc</span><span class="icon"></span></a>" | awk '{for(i=1; i<=NF; ++i)printf "%s%s", $i, (i<NFi?FS:(i<NF?"\n":RS))}'

gives me:

<a
href=abc.com
aria-label=abc
ofe
class=abc><span
class=bcd>abc</span><span
class=icon></span></a>

Trying to get "attribute" string before double quote and "attribute value" string between double quote.

Need to use awk or sed for macOS.

3 Answers

With your shown samples, you could try following awk code. Simple explanation would be, set RS(record separator) to different values(shown by OP required in output) and then print respective values.

awk -v RS='href="[^"]*"|aria-label="[^"]*"|class="[^"]*"' 'RT{print RT}' Input_file

With GNU awk and a regex:

awk '{$1=$1}1' FPAT='[^= ]+="[^"]+"' OFS="\n" file

Output:

href="abc.com"
aria-label="abc ofe"
class="abc"
class="bcd"
class="icon"

FPAT: A regular expression describing the contents of the fields in a record. When set, gawk parses the input into fields, where the fields match the regular expression, instead of using the value of FS as the field separator.

See: man awk and 8 Powerful Awk Built-in Variables – FS, OFS, RS, ORS, NR, NF, FILENAME, FNR

Try this Perl solution:

$ cat sharad.txt
<a href="abc.com" aria-label="abc ofe" class="abc"><span class="bcd">abc</span><span class="icon"></span></a>
$ perl -0777 -ne ' while(/\<([^>]+)>/sg){ $a=$1; while($a=~/(\S+?\".+?\")/mg) { print "$1\n" } } ' sharad.txt
href="abc.com"
aria-label="abc ofe"
class="abc"
class="bcd"
class="icon"
$
Related