我必须查询一个jason文件来检索service_name的值,然后取值,删除双引号,将空格转换为破折号,然后将大写转换为小写。
这是我的json production.json文件
{
"port": 5000,
"machine": "102",
"ip": "xxx.xxx.xxx.xxx",
"drum_id": "1305145216186552",
"client": {
"service_name": "Two Men And A Truck",
"vendor": "default"
}
}
这是我的命令
jq '"\(.client.service_name)"' /home/systems/clients/000002/production.json | sed 's/"//g;s/ /-/g;s/\(.*\)/\L\1/'
这很好用。
root@0200 ~ # cat /home/systems/clients/000002/production.json
{
"port": 5000,
"machine": "102",
"ip": "xxx.xxx.xxx.xxx",
"drum_id": "1305145216186552",
"client": {
"service_name": "Two Men And A Truck",
"vendor": "default"
}
}
root@0200 ~ # jq '"\(.client.service_name)"' /home/systems/clients/000002/production.json | sed 's/"//g;s/ /-/g;s/\(.*\)/\L\1/'
two-men-and-a-truck
现在这是我的初始脚本。这一切都是通过vlan atm完成的,我最终将通过ssh隧道运行它。
#!/bin/bash
#
#-- tmp files
tmp_dir="$(mktemp -d -t 'text.XXXXX' || mktemp -d 2>/dev/null)"
tmp_input1="${tmp_dir}/temp_input1.txt"
tmp_input2="${tmp_dir}/temp_input2.txt"
tmp_input3="${tmp_dir}/temp_input3.txt"
#- servers
cbservers=( "xxx.xxx.xxx.xxx" "xxx.xxx.xxx.xxx" )
for cbserver in "${cbservers[*]}"; do
ssh user@"$cbserver" "ls /home/systems/clients | grep '^[0-9]'" > "$tmp_input1"
while read client; do
ssh user@"$cbserver" "jq '"\(.client.service_name)"' /home/systems/clients/000002/production.json | sed 's/"//g;s/ /-/g;s/\(.*\)/\L\1/'" > "$tmp_input3"
done<"$tmp_input1"
done
rm -rf "$tmp_dir"
尝试打包通过ssh发送的命令时,我真费劲。
ssh user@"$cbserver" "jq '"\(.client.service_name)"' /home/systems/clients/000002/production.json | sed 's/"//g;s/ /-/g;s/\(.*\)/\L\1/'" > "$tmp_input3"
如果有更简便的方法,请赐教。
更新
我遵循了下面所有人的建议
#!/bin/bash
#
#-- tmp files
tmp_dir="$(mktemp -d -t 'text.XXXXX' || mktemp -d 2>/dev/null)"
tmp_input1="${tmp_dir}/temp_input1.txt"
tmp_input2="${tmp_dir}/temp_input2.txt"
#- servers
cbservers=( "xxx.xxx.xxx.xxx" "xxx.xxx.xxx.xxx" )
for cbserver in "${cbservers[*]}"; do
ssh user@"$cbserver" "ls /home/systems/clients | grep '^[0-9]'" > "$tmp_input1"
while read client; do
file="/home/systems/clients/${client}/production.json "
ssh user@"$cbserver" jq --raw-output '.client.service_name' "$file" | sed 's/ /-/g;s/\(.*\)/\L\1/' > "$tmp_input2"
done<"$tmp_input1"
done
rm -rf "$tmp_dir"
“边读客户端”循环仅运行一次,并且应该运行12次。
答案 0 :(得分:1)
您不需要引用整个命令,可以提供多个参数。我会这样做:
file=/home/systems/clients/000002/production.json
...
ssh user@"$cbserver" jq -r '.client.service_name' "$file" | perl -lnE 's/\s+/-/g; say lc' > "$tmp_input3"
注意:
perl
命令将在您的本地系统上运行。 jq -r
来避免引号。答案 1 :(得分:1)
您可以在jq
本身中完成所有这些操作:
$ jq -r '.client.service_name | ascii_downcase | split(" ") | join("-")' <<EOF
{
"port": 5000,
"machine": "102",
"ip": "xxx.xxx.xxx.xxx",
"drum_id": "1305145216186552",
"client": {
"service_name": "Two Men And A Truck",
"vendor": "default"
}
}
EOF
two-men-and-a-truck