2017-07-30 43 views
0

我需要更新近100个包含15-20个表单字段的HTML页面。使用bash,grep和sed批量更新表单字段名称和ID

要通过Section 508合规性,他们都需要唯一命名。

每个表单组有三个像这样相同的属性值的:

<label for="input-title" class="control-label">Title*</label> 
<input class="form-control" id="input-title" name="input-title" value="SA Analyst" required> 

通知之为,名称和id属性都是一样的。

我只需要它是这样的,并在最后一个增量数字:

<label for="input-title21" class="control-label">Title*</label> 
<input class="form-control" id="input-title21" name="input-title21" value="SA Analyst" required> 

面临的挑战是: - 遍历一个HTML文件中的所有表单域(见下面的正则表达式) - 用每个“form-group”更新后面的三个属性值“for,name and id”来更新每个“form-group” - 确保每个form-group具有相同的附加增量数字(即每三个属性会在当前循环中得到相同的数字)

这里是开始bash的代码我一起工作:

#!/bin/bash 
FILES=/Users/Administrator/files/*.html 
counter=1 
for f in $FILES 
do 
    echo "Processing $f file..." 
    # take action on each file. $f store current file name 
    # cat $f 
    # sed 's/<input/<input2/g' $f > $f.txt 

    sed "s/<input/<input$counter/g" $f > $f.txt 

    echo $counter 
    ((counter++)) 


done 
echo All done 

此代码成功更新与计数器变量数输入,并将其保存为.txt文件,但是这还不是因为它更新所有输入字段解决方案具有相同递增数字的HTML文件。

这里是我想出了正则表达式与认定,需要改变的形式组:

(.*for\=")([0-9A-Za-z-]+)(".*\n\s*[0-9A-Za-z\<\>\-\=\"\s]*[id=|name=]")([0-9A-Za-z-]+)(".*[id=|name=]")([0-9A-Za-z-]+)("\s[type|req]) 

那么,如何在各种形式的整合这个表达式与上面的bash的代码和更新三个属性-组?

+1

我建议使用XML/HTML解析器(xmlstarlet,xmllint ...)。 – Cyrus

+0

你有这样的例子吗?谢谢 –

回答

0

随着mawk:

scriptfile1:

/label for=\"input-title\"/ { 
     num++ 
     } 
{ 
     gsub("label for=\"input-title\"","label for=\"input- 
title"num"\"") 
     gsub("id=\"input-title\"","id=\"input-title"num"\"") 
     gsub("name=\"input-title\"","name=\"input-title"num"\"") 
     print 
} 

这里我们增加一个计数器(NUM)每次我们遇到了=“输入文本”的文本标签,然后我们检查的三个实例时间使用gensub在每个段中输入文本(for =,id =和name =),并更改它们以添加num变量。我们最终打印重建线。

运行带:

awk -f scriptfile1 sourcedatafilename 
+0

我试着运行你的代码,并得到这个:awk:未终止的字符串标签= ...在源代码行6源文件scriptfile1 上下文是 \t $ 0 = gensub(“label for = \”input-title \“ “,”label for = \“输入 - >>> <<< –

+0

必须是您的awk版本 –

+0

awk版本20070501 –