官术网_书友最值得收藏!

How it works...

We have already discussed several important aspects such as the power of the SED and AWK commands, and even CSVs, but we have not discussed the importance of being able to transform the format and structure of data. CSVs are a fundamental and very common format of data, but unfortunately, it isn't the best choice for some applications, so we may use XML or JSON. Here are two scripts (or rather one script and one tool) that can convert our original data into various formats:

  1. When executing data-csv-to-xml.sh, we notice several things: we utilize two source template files, which can be altered for flexibility, and then a large piped command that leverages sed and AWK. On input, we take each of the CSV values and build a <word lang="x">Y</word> XML element using the format template inside of word.tpl, where $0 is field one and $1 is field two. The script will produce a words.csv and output the following:
$ bash data-csv-to-xml.sh
<?xml version="1.0" encoding="UTF-8"?>
<words type="greeting">
<word lang="EN">"Hello"</word>
<word lang="FR">"Bonjour"</word>
</words>
  1. In the second script, we merely take words.xml as input into the command xml2json. The output will be in JSON format. Cool hey?
!#/bin/bash
{
"words": {
"type": "greeting",
"word": [
{
"lang": "EN",
"$t": "\"Hello\""
},
{
"lang": "FR",
"$t": "\"Bonjour\""
}
]
}
}
The differences and reasons between all three formats of data (CSV, XML, and JSON) is left as an exercise for the reader to discover. Another exercise to explore is performing data validation to ensure integrity and constraints on data. For example, XML can use XSD schemas to enforce data limits.
主站蜘蛛池模板: 舒城县| 和林格尔县| 婺源县| 广州市| 武乡县| 罗山县| 梁平县| 萨迦县| 恭城| 海阳市| 济源市| 成都市| 习水县| 洪江市| 锦屏县| 出国| 定边县| 平塘县| 建阳市| 婺源县| 札达县| 土默特右旗| 枣阳市| 策勒县| 托里县| 紫金县| 油尖旺区| 浏阳市| 修武县| 朝阳区| 宁武县| 章丘市| 莱芜市| 昆山市| 莆田市| 石嘴山市| 麻栗坡县| 上高县| 滁州市| 房山区| 乳山市|