- 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 網頁編程從入門到精通 (清華社"視頻大講堂"大系·網絡開發視頻大講堂)
- 精通搜索分析
- Getting Started with CreateJS
- Serverless架構
- Instant Ext.NET Application Development
- Learning Unity 2D Game Development by Example
- HTML5權威指南
- 監控的藝術:云原生時代的監控框架
- Python Web自動化測試設計與實現
- Python+Office:輕松實現Python辦公自動化
- JavaScript Concurrency
- Spring Boot從入門到實戰
- ArcPy and ArcGIS(Second Edition)
- Web前端測試與集成:Jasmine/Selenium/Protractor/Jenkins的最佳實踐
- 計算思維與Python編程