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

  • Bash Cookbook
  • Ron Brash Ganesh Naik
  • 265字
  • 2021-07-23 19:17:41

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.
主站蜘蛛池模板: 增城市| 云阳县| 上思县| 浙江省| 根河市| 普格县| 东丽区| 平顺县| 吉木萨尔县| 贡觉县| 南开区| 区。| 响水县| 七台河市| 阿拉善盟| 连云港市| 疏附县| 宁陕县| 泸定县| 九江县| 兰州市| 安庆市| 朝阳市| 晋城| 三亚市| 花莲市| 寻乌县| 信宜市| 青海省| 恩施市| 鲜城| 博客| 高尔夫| 博湖县| 思南县| 揭西县| 武隆县| 蓬安县| 虎林市| 石台县| 德钦县|