Home > Software design >  How to format text file into table format using sed and grep
How to format text file into table format using sed and grep

Time:06-14

enter image description here

$grep -rlZ "$pattern" /path/of/file/ | xargs -0 grep -rZ "$pattern" | sed -e 's~.*=\(.*\)~<tr><td>\1</td></tr>~;1i\<html><table border="1">' -e '$a\</table>\n</html>`;

How to get the expected output by altering the above sed command

Expected Output

<html><table border="1">
 <tr><td>Aastha</td>
 <td>Rohini</td>
 <td>Delhi</td>
 <td>20</td>
 <td>India</td>
 </tr>
 <tr>
 <td>Aastha</td>
 <td>Dwarka</td>
 <td>Delhi</td>
 <td>20</td>
 <td>India</td>
 </tr>
 </table>
  </html>

Example of data in the files:

name==ABC
City==Rohini
State==Delhi
Age==18
Country==India

CodePudding user response:

As you are trying to execute the command on numerous similar files, using find would be better suited to achieve the expected output

$ cat file1
name==ABC
City==Rohini
State==Delhi
Age==18
Country==India

$ cat file2
name==DEF
City==Rohini
State==Delhi
Age==22
Country==India
$ find /path/to/file -type f -name 'file*' -exec sed -e '/name\|city\|country\|state\|age/I{1s~.*=\(.*\)~<tr><td>\1</td>~;s~.*=\(.*\)~<td>\1</td>~;$a\</tr>' -e '}' {} \; | sed -e '1i\<html><table border="1">' -e '$a\</table>\n</html>'
<html><table border="1">
<tr><td>ABC</td>
<td>Rohini</td>
<td>Delhi</td>
<td>18</td>
<td>India</td>
</tr>
<tr><td>DEF</td>
<td>Rohini</td>
<td>Delhi</td>
<td>22</td>
<td>India</td>
</tr>
</table>
</html>
  • Related