将Bash字符串转换为JavaString

时间:2019-03-13 11:08:54

标签: java string bash sh implicit-conversion

我想将bash变量中存在的String转换为Java Supported String样式。

例如: data="{"5": ">10%", "4": "<5%", "3": ">28 months", "2": "20%", "1": 100}"

echo $data

给我这个结果:

    "{\n" + 
    "    \"1\": 21,\n" + 
    "    \"2\": \"40%\",\n" + 
    "    \"3\": \"<24 months\",\n" + 
    "    \"4\": \"<5%\",\n" + 
    "    \"5\": \">10%\"\n" + 
    "}"

但是我还需要使用echo "String data = $data;" >> file.txt将此值传输到文件中,其中数据是经过处理的值,在该数据中它会抛出奇怪的结果,例如

String data = "{
" + 
"   \"5\": \">10%\",
" + 
"   \"4\": \"<5%\",
" + 
"   \"3\": \">28 months\",
" + 
"   \"2\": \"20%\",
" + 
"   \"1\": 100
" + 
"}";

但预期是:

String data = "{\n" + 
        "   \"1\": 50,\n" + 
        "   \"2\": \"40%\",\n" + 
        "   \"3\": \">28 months\",\n" + 
        "   \"4\": \"<5%\",\n" + 
        "   \"5\": \">10%\"\n" + 
        "}";

1 个答案:

答案 0 :(得分:1)

使用大大adhoc的方法: (调用perl 两次

data='{"5": ">10%", "4": "<5%", "3": ">28 months", "2": "20%", "1": 100}'
echo $data |\
perl -pe 's/{/{\n/; s/}/\n}/; s/, /,\n/g; s/^"/   "/gm' |\
perl -0pe 's/"/\\"/g; s/\n/\\n" + \n/g; s/^/"/gm; s/\}\\n.*$/}"/'

结果是:

 "{\n" +
 "   \"5\": \">10%\",\n" +
 "   \"4\": \"<5%\",\n" +
 "   \"3\": \">28 months\",\n" +
 "   \"2\": \"20%\",\n" +
 "   \"1\": 100\n" +
 "}"

进一步测试:

test='{"first" : "1st", "second": "2nd", "third" : "3rd" }'

echo $test |\
 perl -pe 's/{/{\n/; s/}/\n}/; s/, /,\n/g; s/^"/   "/gm' |\
 perl -0pe 's/"/\\"/g; s/\n/\\n" + \n/g; s/^/"/gm; s/\}\\n.*$/}"/'

返回

"{\n" +
"   \"first\" : \"1st\",\n" +
"   \"second\": \"2nd\",\n" +
"   \"third\" : \"3rd\" \n" +
"}" 

关于输出此新字符串,请尝试:

data='{"5": ">10%", "4": "<5%", "3": ">28 months", "2": "20%", "1": 100}'
newdata=$(echo $data |\
perl -pe 's/{/{\n/; s/}/\n}/; s/, /,\n/g; s/^"/   "/gm' |\
perl -0pe 's/"/\\"/g; s/\n/\\n" + \n/g; s/^/"/gm; s/\}\\n.*$/}"/')

echo "String data = $newdata" >> /tmp/file.txt

关于更新(*使用sh代替bash,并获得2个\t *),请尝试以下操作 (越来越难看了...'):

data='{"5": ">10%", "4": "<5%", "3": ">28 months", "2": "20%", "1": 100}'
newdata=$(echo $data |\
perl -pe 's/{/{\n/; s/}/\n}/; s/, /,\n/g; ' |\
perl -0pe 's/"/\\"/g; s/\n/\\n" + \n/g; s/^/"/gm; s/^"/\t\t"/gm; s/^\t\t"/"/; s/\}\\n.*$/}"/')

/bin/echo "String data = $newdata" >> /tmp/file.txt