- 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.
推薦閱讀
- JavaScript前端開發(fā)模塊化教程
- 國際大學(xué)生程序設(shè)計(jì)競賽中山大學(xué)內(nèi)部選拔真題解(二)
- Node.js 10實(shí)戰(zhàn)
- Python快樂編程:人工智能深度學(xué)習(xí)基礎(chǔ)
- SQL語言從入門到精通
- C語言程序設(shè)計(jì)案例式教程
- Oracle BAM 11gR1 Handbook
- Functional Kotlin
- 概率成形編碼調(diào)制技術(shù)理論及應(yīng)用
- Learning Hunk
- Visual Basic程序設(shè)計(jì)教程
- Visual Basic程序設(shè)計(jì)習(xí)題與上機(jī)實(shí)踐
- TypeScript 2.x By Example
- RESTful Web API Design with Node.js(Second Edition)
- React.js實(shí)戰(zhàn)