将Bash字符串转换为Java字符串

问题描述 投票:2回答:1

我想将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" + 
        "}";
java string bash sh implicit-conversion
1个回答
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个\ts *),请尝试以下(它变得更丑陋和丑陋......):

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
© www.soinside.com 2019 - 2024. All rights reserved.