tags:

views:

36

answers:

2

My HTML code has the following line.

<TH>column1</TH><TH>column2</TH><TH>column3</TH>

Can I use sed tool to replace the column1 with "Name", column2 with "Surname" ...

<TH>Name</TH><TH>Surname</TH><TH>City</TH>

I have the list of the columns in a echo statement of my shell script.

echo 'Name, Surname, City'

These 3 values needs to be replaced in the respective columns in the HTML code. The number of columns might change.

+3  A: 

Can you change the input format of the new column names, or are you stuck with the echo. And does the table header line appear once per html file, or multiple times?

For your current situation, this would work:

echo 'Name, Surname, City' |
awk -F'<TH>|</TH><TH>|</TH>' 'NR==1{n=split($0,a,", *");OFS="";next}/<TH>/{for(i=1; i<=n;i++)$(i+1)="<TH>"a[i]"</TH>"}1' - file.html

Output:

<TH>Name</TH><TH>Surname</TH><TH>City</TH>

Note that things will go horribly wrong when your input html has a different form (additional or missing newlines). If you want to do anything more advanced you should use a proper SGML parser instead of awk or sed.

schot
Thanks. But how do I replace the file with the new contents? sed has -i swith. awk?
shantanuo
schot
A: 

put your replacements into variables instead of doing echo, then simply

sed 's|<TH>column1<\/TH>|<TH>Name</TH>|;s|<TH>column2</TH>|<TH>Surname</TH>|;s|<TH>column3</TH>|<TH>City</TH>|' file

Note, this is not fool proof if your pattern span multiple lines. But if all the things you need replaced is on one line, then it should be all right.

ghostdog74