- 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:
- 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>
- 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.
推薦閱讀
- 深度實踐OpenStack:基于Python的OpenStack組件開發
- 觸·心:DT時代的大數據精準營銷
- 潮流:UI設計必修課
- Java Web程序設計
- Linux環境編程:從應用到內核
- Unity Shader入門精要
- 網店設計看這本就夠了
- Visual C++數字圖像處理技術詳解
- Service Mesh實戰:基于Linkerd和Kubernetes的微服務實踐
- 基于ARM Cortex-M4F內核的MSP432 MCU開發實踐
- 一塊面包板玩轉Arduino編程
- SQL Server實用教程(SQL Server 2008版)
- 搞定J2EE:Struts+Spring+Hibernate整合詳解與典型案例
- 移動互聯網軟件開發實驗指導
- Citrix XenServer企業運維實戰