我有一个html文件,其中包含我正在处理的一个项目的依赖项列表。它的格式如下:
--一些html
<p><strong>Module Name:</strong> spring-web</p>
<p><strong>Module Group:</strong> org.springframework</p>
<p><strong>Module Version:</strong> 4.2.1.RELEASE</p>--更多html
<p><strong>Module Name:</strong> google-http-client</p>
<p><strong>Module Group:</strong> com.google.http-client</p>
<p><strong>Module Version:</strong> 1.19.0</p>等
我想从这个html文件创建一个csv文件,csv文件将具有每个记录的格式:
模块名称、模块组、模块版本
例如google-http-client,com.google.http-client,1.19.0
你知道怎么用脚本做到这一点吗?
发布于 2015-12-08 22:10:08
试试看!
#!/bin/bash
inFile=$1
outFile=$2
join () {
local del=$1
shift
IFS="$del"
source <(
cat <<SOURCE
echo "\${$1[*]}"
SOURCE
)
unset IFS
}
declare -a CSV=('"Module Name","Module Group","Module Version"')
declare -a keysAccepted=('Name' 'Group' 'Version')
declare -i nMandatoryKeys=${#keysAccepted[@]}
declare -A KeyFilled
rxKeysAccepted='('$(join '|' keysAccepted)')'
while read line; do
[[ $line =~ \<strong\>Module\ $rxKeysAccepted:\</strong\>[[:space:]]*([^<]+)\</p\> ]] || continue
key=${BASH_REMATCH[1]}
val=${BASH_REMATCH[2]}
KeyFilled[$key]=$val
if (( ${#KeyFilled[@]} == nMandatoryKeys )); then
unset csvLine
for k in ${keysAccepted[@]}; do
csvLine+=${csvLine:+,}${KeyFilled[$k]}
done
KeyFilled=()
CSV+=($csvLine)
fi
done <"$inFile"
(( ${#CSV[@]} > 1 )) || exit 1
join $'\x0a' CSV >"$outFile"发布于 2015-12-09 04:41:07
如果你的源文件是一致的(所有三个字段以相同的顺序同时存在),你可以尝试这样做...
$ sed -nr 's_\s*<p><strong>Module (Name|Group|Version):</strong> (.*)</p>_\2_p' file\
| awk 'ORS=NR%3?",":RS'
spring-web,org.springframework,4.2.1.RELEASE
google-http-client,com.google.http-client,1.19.0https://stackoverflow.com/questions/34153237
复制相似问题