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

  • Bash Cookbook
  • Ron Brash Ganesh Naik
  • 197字
  • 2021-07-23 19:17:40

How to do it...

Let's begin our activity as follows:

  1. Open a terminal and create the data-csv-to-xml.sh script with the following contents. Then, execute the script after saving it using $ bash data-csv-to-xml.sh:
#!/bin/bash

# Import template variables
source xml-parent.tpl
source word.tpl

OUTPUT_FILE="words.xml"
INPUT_FILE="words.csv"
DELIMITER=','

# Setup header
echo ${XML_HDR} > ${OUTPUT_FILE}
echo ${SRT_CONTR} >> ${OUTPUT_FILE}

# Enter content
echo ${ELM} | \
sed '{:q;N;s/\n/\\n/g;t q}'| \
awk \
'{ print "awk \x27 BEGIN{FS=\"'${DELIMITER}'\"}{print "$0"}\x27 '${INPUT_FILE}'"}' | \
sh >> ${OUTPUT_FILE}

# Append trailer
echo ${END_CONTR} >> ${OUTPUT_FILE}

cat ${OUTPUT_FILE}
  1. Examine the output, but be aware that "pretty" XML isn't necessary and in fact, we don't even need to have the XML on multiple lines. If pure data is required for a web application, the extra new lines and tabs are unnecessary data to be transmitted.
  2. Create another script named data-xml-to-json.sh with the following contents. Then, execute the script after saving it using  data-xml-to-json.sh:
!#/bin/bash
INPUT_FILE"words.xml"
OUTPUT_FILE="words.json"

# Easy one line!
xml2json < ${INPUT_FILE} ${OUTPUT_FILE}
  1. Review the output and see how it easy it is! Are there areas you could improve on in both of the scripts?
主站蜘蛛池模板: 潞西市| 元氏县| 益阳市| 阿克苏市| 麻城市| 大洼县| 乌兰浩特市| 蓬莱市| 柞水县| 武汉市| 台南县| 嘉鱼县| 渭源县| 漳州市| 土默特右旗| 壤塘县| 山西省| 荥阳市| 蓬溪县| 新乡市| 湘阴县| 洪雅县| 甘德县| 高平市| 迁安市| 尚义县| 黄大仙区| 诸城市| 衡南县| 福建省| 凤台县| 霍林郭勒市| 河西区| 双柏县| 七台河市| 吉安县| 崇仁县| 宁津县| 天台县| 商都县| 昌江|