有时候我们在对lsf的节点负载进行分析的时候,需要进行一些格式的裁剪和切换。
目测当前最友好的格式是json
下面是将lsload的结果转换成json的一个脚本,请勿照搬!
#!/bin/bash # 获取lsload结果 load_data=$(lsload | awk '{print $1" "$2" "$3" "$4" "$5" "$6" "$7" "$8" "$9" "$10" "$11}') # 转换为JSON格式 json_data='[' for line in $load_data; do # 提取每个字段 host=$(echo $line | awk '{print $1}') status=$(echo $line | awk '{print $2}') r15s=$(echo $line | awk '{print $3}') r1m=$(echo $line | awk '{print $4}') r15m=$(echo $line | awk '{print $5}') ut=$(echo $line | awk '{print $6}') pg=$(echo $line | awk '{print $7}') ls=$(echo $line | awk '{print $8}') it=$(echo $line | awk '{print $9}') tmp=$(echo $line | awk '{print $10}') swp=$(echo $line | awk '{print $11}') mem=$(echo $line | awk '{print $12}') # 添加到JSON数据中 json_data+='{"host":"'$host'", "status":"'$status'", "r15s":"'$r15s'", "r1m":"'$r1m'", "r15m":"'$r15m'", "ut":"'$ut'", "pg":"'$pg'", "ls":"'$ls'", "it":"'$it'", "tmp":"'$tmp'", "swp":"'$swp'", "mem":"'$mem'"},' done # 去除最后一个逗号并添加闭合方括号 json_data=${json_data%?}']' # 输出JSON数据 echo $json_data
如果要用一行命令来处理,请使用如下,注意,需要是bash脚本环境
echo "[" $(lsload | awk 'NR>1 {printf "%s{\"hostname\":\"%s\",\"status\":\"%s\",\"r15s\":\"%s\",\"r1m\":\"%s\",\"r15m\":\"%s\",\"ut\":\"%s\",\"pg\":\"%s\",\"ls\":\"%s\",\"it\":\"%s\",\"tmp\":\"%s\",\"swp\":\"%s\",\"mem\":\"%s\"}", (NR>2 ? "," : ""), $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12}') "]"
csh下由于不可以是用$(),则可以使用如下命令
echo "[" `lsload | awk 'NR>1 {printf "%s{\"hostname\":\"%s\",\"status\":\"%s\",\"r15s\":\"%s\",\"r1m\":\"%s\",\"r15m\":\"%s\",\"ut\":\"%s\",\"pg\":\"%s\",\"ls\":\"%s\",\"it\":\"%s\",\"tmp\":\"%s\",\"swp\":\"%s\",\"mem\":\"%s\"}", (NR>2 ? "," : ""), $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12}'` "]"
网友留言: