- 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.
推薦閱讀
- 從零開始構(gòu)建企業(yè)級RAG系統(tǒng)
- JSP網(wǎng)絡(luò)編程(學(xué)習(xí)筆記)
- Mastering SVG
- PHP+MySQL網(wǎng)站開發(fā)技術(shù)項目式教程(第2版)
- JavaScript從入門到精通(第3版)
- Learning Python Design Patterns(Second Edition)
- 西門子S7-200 SMART PLC編程從入門到實踐
- Building Wireless Sensor Networks Using Arduino
- C/C++數(shù)據(jù)結(jié)構(gòu)與算法速學(xué)速用大辭典
- 進(jìn)入IT企業(yè)必讀的324個Java面試題
- SAP Web Dynpro for ABAP開發(fā)技術(shù)詳解:基礎(chǔ)應(yīng)用
- Java并發(fā)實現(xiàn)原理:JDK源碼剖析
- Software Architecture with Python
- ASP.NET本質(zhì)論
- Oracle API Management 12c Implementation