how to convert json file data to string in bash shell script?
how to convert json file data to string in bash shell script? i have below petstore swagger file (https://petstore.swagger.io/v2/swagger.json) in json format. i have converted this json file into string with backspaces characters \ needed for one operation using this site https://jsontostring.com/ . i have tried jq tool to achieve this, didn’t got the result and perhaps it will not come using jq tool. How can we convert this same petstore swagger json file into string with below expected output in linux or bash shell script ?
,"license":>,"host":"petstore.swagger.io","basePath":"/v2","tags":[>,,>],"schemes":["https","http"],"paths":/uploadImage":,,],"responses":>>,"security":[]>>,"/pet":>],"responses":>,"security":[]>,"put":>],"responses":,"404":,"405":>,"security":[]>>,"/pet/findByStatus":,"collectionFormat":"multi">],"responses":>>,"400":>,"security":[]>>,"/pet/findByTags":,"collectionFormat":"multi">],"responses":>>,"400":>,"security":[],"deprecated":true>>,"/pet/":],"responses":>,"400":,"404":>,"security":[<"api_key":[]>]>,"post":,,],"responses":>,"security":[]>,"delete":,],"responses":,"404":>,"security":[]>>,"/store/order":>],"responses":>,"400":>>>,"/store/order/":= 1 and ],"responses":>,"400":,"404":>>,"delete":],"responses":,"404":>>>,"/store/inventory":>>>,"security":[<"api_key":[]>]>>,"/user/createWithArray":>>],"responses":>>>,"/user/createWithList":>>],"responses":>>>,"/user/":],"responses":>,"400":,"404":>>,"put":,>],"responses":,"404":>>,"delete":],"responses":<"400":,"404":>>>,"/user/login":,],"responses":,"X-Rate-Limit":>,"schema":>,"400":>>>,"/user/logout":<"get":<"tags":["user"],"summary":"Logs out current logged in user session","description":"","operationId":"logoutUser","produces":["application/json","application/xml"],"parameters":[],"responses":>>>,"/user":>],"responses":>>>>,"securityDefinitions":,"petstore_auth":>>,"definitions":,"type":,"message":>>,"Category":,"name":>,"xml":>,"Pet":,"category":,"name":,"photoUrls":,"items":>>,"tags":,"items":,"$ref":"#/definitions/Tag">>,"status":>,"xml":>,"Tag":,"name":>,"xml":>,"Order":,"petId":,"quantity":,"shipDate":,"status":,"complete":>,"xml":>,"User":,"username":,"firstName":,"lastName":,"email":,"password":,"phone":,"userStatus":>,"xml":>>,"externalDocs":>
"<\"swagger\":\"2.0\",\"info\":<\"description\":\"ThisisasampleserverPetstoreserver.YoucanfindoutmoreaboutSwaggerat[http://swagger.io](http://swagger.io)oron[irc.freenode.net,#swagger](http://swagger.io/irc/).Forthissample,youcanusetheapikey`special-key`totesttheauthorizationfilters.\",\"version\":\"1.0.6\",\"title\":\"SwaggerPetstore\",\"termsOfService\":\"http://swagger.io/terms/\",\"contact\":<\"email\":\"apiteam@swagger.io\">,\"license\":>,\"host\":\"petstore.swagger.io\",\"basePath\":\"/v2\",\"tags\":[>,,>],\"schemes\":[\"https\",\"http\"],\"paths\":/uploadImage\":<\"post\":<\"tags\":[\"pet\"],\"summary\":\"uploadsanimage\",\"description\":\"\",\"operationId\":\"uploadFile\",\"consumes\":[\"multipart/form-data\"],\"produces\":[\"application/json\"],\"parameters\":[<\"name\":\"petId\",\"in\":\"path\",\"description\":\"IDofpettoupdate\",\"required\":true,\"type\":\"integer\",\"format\":\"int64\">,,],\"responses\":>>,\"security\":[]>>,\"/pet\":<\"post\":<\"tags\":[\"pet\"],\"summary\":\"Addanewpettothestore\",\"description\":\"\",\"operationId\":\"addPet\",\"consumes\":[\"application/json\",\"application/xml\"],\"produces\":[\"application/json\",\"application/xml\"],\"parameters\":[<\"in\":\"body\",\"name\":\"body\",\"description\":\"Petobjectthatneedstobeaddedtothestore\",\"required\":true,\"schema\":<\"$ref\":\"#/definitions/Pet\">>],\"responses\":>,\"security\":[]>,\"put\":<\"tags\":[\"pet\"],\"summary\":\"Updateanexistingpet\",\"description\":\"\",\"operationId\":\"updatePet\",\"consumes\":[\"application/json\",\"application/xml\"],\"produces\":[\"application/json\",\"application/xml\"],\"parameters\":[<\"in\":\"body\",\"name\":\"body\",\"description\":\"Petobjectthatneedstobeaddedtothestore\",\"required\":true,\"schema\":<\"$ref\":\"#/definitions/Pet\">>],\"responses\":,\"404\":,\"405\":>,\"security\":[]>>,\"/pet/findByStatus\":<\"get\":<\"tags\":[\"pet\"],\"summary\":\"FindsPetsbystatus\",\"description\":\"Multiplestatusvaluescanbeprovidedwithcommaseparatedstrings\",\"operationId\":\"findPetsByStatus\",\"produces\":[\"application/json\",\"application/xml\"],\"parameters\":[<\"name\":\"status\",\"in\":\"query\",\"description\":\"Statusvaluesthatneedtobeconsideredforfilter\",\"required\":true,\"type\":\"array\",\"items\":<\"type\":\"string\",\"enum\":[\"available\",\"pending\",\"sold\"],\"default\":\"available\">,\"collectionFormat\":\"multi\">],\"responses\":>>,\"400\":>,\"security\":[]>>,\"/pet/findByTags\":<\"get\":<\"tags\":[\"pet\"],\"summary\":\"FindsPetsbytags\",\"description\":\"Multipletagscanbeprovidedwithcommaseparatedstrings.Usetag1,tag2,tag3fortesting.\",\"operationId\":\"findPetsByTags\",\"produces\":[\"application/json\",\"application/xml\"],\"parameters\":[<\"name\":\"tags\",\"in\":\"query\",\"description\":\"Tagstofilterby\",\"required\":true,\"type\":\"array\",\"items\":,\"collectionFormat\":\"multi\">],\"responses\":>>,\"400\":>,\"security\":[],\"deprecated\":true>>,\"/pet/\":<\"get\":<\"tags\":[\"pet\"],\"summary\":\"FindpetbyID\",\"description\":\"Returnsasinglepet\",\"operationId\":\"getPetById\",\"produces\":[\"application/json\",\"application/xml\"],\"parameters\":[<\"name\":\"petId\",\"in\":\"path\",\"description\":\"IDofpettoreturn\",\"required\":true,\"type\":\"integer\",\"format\":\"int64\">],\"responses\":>,\"400\":,\"404\":>,\"security\":[<\"api_key\":[]>]>,\"post\":<\"tags\":[\"pet\"],\"summary\":\"Updatesapetinthestorewithformdata\",\"description\":\"\",\"operationId\":\"updatePetWithForm\",\"consumes\":[\"application/x-www-form-urlencoded\"],\"produces\":[\"application/json\",\"application/xml\"],\"parameters\":[<\"name\":\"petId\",\"in\":\"path\",\"description\":\"IDofpetthatneedstobeupdated\",\"required\":true,\"type\":\"integer\",\"format\":\"int64\">,,],\"responses\":>,\"security\":[]>,\"delete\":<\"tags\":[\"pet\"],\"summary\":\"Deletesapet\",\"description\":\"\",\"operationId\":\"deletePet\",\"produces\":[\"application/json\",\"application/xml\"],\"parameters\":[<\"name\":\"api_key\",\"in\":\"header\",\"required\":false,\"type\":\"string\">,],\"responses\":,\"404\":>,\"security\":[]>>,\"/store/order\":<\"post\":<\"tags\":[\"store\"],\"summary\":\"Placeanorderforapet\",\"description\":\"\",\"operationId\":\"placeOrder\",\"consumes\":[\"application/json\"],\"produces\":[\"application/json\",\"application/xml\"],\"parameters\":[<\"in\":\"body\",\"name\":\"body\",\"description\":\"orderplacedforpurchasingthepet\",\"required\":true,\"schema\":<\"$ref\":\"#/definitions/Order\">>],\"responses\":>,\"400\":>>>,\"/store/order/\":=1and<=10.Othervalueswillgeneratedexceptions\",\"operationId\":\"getOrderById\",\"produces\":[\"application/json\",\"application/xml\"],\"parameters\":[<\"name\":\"orderId\",\"in\":\"path\",\"description\":\"IDofpetthatneedstobefetched\",\"required\":true,\"type\":\"integer\",\"maximum\":10,\"minimum\":1,\"format\":\"int64\">],\"responses\":>,\"400\":,\"404\":>>,\"delete\":<\"tags\":[\"store\"],\"summary\":\"DeletepurchaseorderbyID\",\"description\":\"ForvalidresponsetryintegerIDswithpositiveintegervalue.Negativeornon-integervalueswillgenerateAPIerrors\",\"operationId\":\"deleteOrder\",\"produces\":[\"application/json\",\"application/xml\"],\"parameters\":[<\"name\":\"orderId\",\"in\":\"path\",\"description\":\"IDoftheorderthatneedstobedeleted\",\"required\":true,\"type\":\"integer\",\"minimum\":1,\"format\":\"int64\">],\"responses\":,\"404\":>>>,\"/store/inventory\":<\"get\":<\"tags\":[\"store\"],\"summary\":\"Returnspetinventoriesbystatus\",\"description\":\"Returnsamapofstatuscodestoquantities\",\"operationId\":\"getInventory\",\"produces\":[\"application/json\"],\"parameters\":[],\"responses\":<\"200\":<\"description\":\"successfuloperation\",\"schema\":<\"type\":\"object\",\"additionalProperties\":>>>,\"security\":[<\"api_key\":[]>]>>,\"/user/createWithArray\":<\"post\":<\"tags\":[\"user\"],\"summary\":\"Createslistofuserswithgiveninputarray\",\"description\":\"\",\"operationId\":\"createUsersWithArrayInput\",\"consumes\":[\"application/json\"],\"produces\":[\"application/json\",\"application/xml\"],\"parameters\":[<\"in\":\"body\",\"name\":\"body\",\"description\":\"Listofuserobject\",\"required\":true,\"schema\":<\"type\":\"array\",\"items\":<\"$ref\":\"#/definitions/User\">>>],\"responses\":>>>,\"/user/createWithList\":<\"post\":<\"tags\":[\"user\"],\"summary\":\"Createslistofuserswithgiveninputarray\",\"description\":\"\",\"operationId\":\"createUsersWithListInput\",\"consumes\":[\"application/json\"],\"produces\":[\"application/json\",\"application/xml\"],\"parameters\":[<\"in\":\"body\",\"name\":\"body\",\"description\":\"Listofuserobject\",\"required\":true,\"schema\":<\"type\":\"array\",\"items\":<\"$ref\":\"#/definitions/User\">>>],\"responses\":>>>,\"/user/\":<\"get\":<\"tags\":[\"user\"],\"summary\":\"Getuserbyusername\",\"description\":\"\",\"operationId\":\"getUserByName\",\"produces\":[\"application/json\",\"application/xml\"],\"parameters\":[<\"name\":\"username\",\"in\":\"path\",\"description\":\"Thenamethatneedstobefetched.Useuser1fortesting.\",\"required\":true,\"type\":\"string\">],\"responses\":>,\"400\":,\"404\":>>,\"put\":<\"tags\":[\"user\"],\"summary\":\"Updateduser\",\"description\":\"Thiscanonlybedonebytheloggedinuser.\",\"operationId\":\"updateUser\",\"consumes\":[\"application/json\"],\"produces\":[\"application/json\",\"application/xml\"],\"parameters\":[<\"name\":\"username\",\"in\":\"path\",\"description\":\"namethatneedtobeupdated\",\"required\":true,\"type\":\"string\">,>],\"responses\":,\"404\":>>,\"delete\":<\"tags\":[\"user\"],\"summary\":\"Deleteuser\",\"description\":\"Thiscanonlybedonebytheloggedinuser.\",\"operationId\":\"deleteUser\",\"produces\":[\"application/json\",\"application/xml\"],\"parameters\":[<\"name\":\"username\",\"in\":\"path\",\"description\":\"Thenamethatneedstobedeleted\",\"required\":true,\"type\":\"string\">],\"responses\":<\"400\":,\"404\":>>>,\"/user/login\":<\"get\":<\"tags\":[\"user\"],\"summary\":\"Logsuserintothesystem\",\"description\":\"\",\"operationId\":\"loginUser\",\"produces\":[\"application/json\",\"application/xml\"],\"parameters\":[<\"name\":\"username\",\"in\":\"query\",\"description\":\"Theusernameforlogin\",\"required\":true,\"type\":\"string\">,],\"responses\":,\"X-Rate-Limit\":>,\"schema\":>,\"400\":>>>,\"/user/logout\":<\"get\":<\"tags\":[\"user\"],\"summary\":\"Logsoutcurrentloggedinusersession\",\"description\":\"\",\"operationId\":\"logoutUser\",\"produces\":[\"application/json\",\"application/xml\"],\"parameters\":[],\"responses\":>>>,\"/user\":<\"post\":<\"tags\":[\"user\"],\"summary\":\"Createuser\",\"description\":\"Thiscanonlybedonebytheloggedinuser.\",\"operationId\":\"createUser\",\"consumes\":[\"application/json\"],\"produces\":[\"application/json\",\"application/xml\"],\"parameters\":[<\"in\":\"body\",\"name\":\"body\",\"description\":\"Createduserobject\",\"required\":true,\"schema\":<\"$ref\":\"#/definitions/User\">>],\"responses\":>>>>,\"securityDefinitions\":,\"petstore_auth\":>>,\"definitions\":,\"type\":,\"message\":>>,\"Category\":,\"name\":>,\"xml\":>,\"Pet\":,\"category\":,\"name\":,\"photoUrls\":,\"items\":>>,\"tags\":,\"items\":,\"$ref\":\"#/definitions/Tag\">>,\"status\":>,\"xml\":>,\"Tag\":,\"name\":>,\"xml\":>,\"Order\":,\"petId\":,\"quantity\":,\"shipDate\":,\"status\":,\"complete\":>,\"xml\":>,\"User\":,\"username\":,\"firstName\":,\"lastName\":,\"email\":,\"password\":,\"phone\":,\"userStatus\":>,\"xml\":>>,\"externalDocs\":>"
Convert an output to string
It’s not working; the variable $a ia not compare with the the string «AC adapter : online». How to convert the output of command acpitool -a to a string? This is what happens:
AC adapter : online ./acpower.sh: linha 7: AC: comando não encontrado OFFLINE
#!/bin/bash # set the variable a=$(acpitool -a) # remove white spaces a=$ # echo for test echo $a # compare the result if [[ "$a" == 'ACadapter:online' ]] then # then that the imagination is the limit echo "ONLINE" else # else if you have no imagination you're lost echo "OFFLINE" fi
Welcome to Stack Overflow. Please read the About page soon. You did a nice job on your question; you showed the code, you explained what you wanted and what you got as an error — all good technique.
5 Answers 5
How to fix the problem
The shell (or the test command) uses = for string equality and -eq for numeric equality. Some versions of the shell support == as a synonym for = (but = is defined by the POSIX test command). By contrast, Perl uses == for numeric equality and eq for string equality.
You also need to use one of the test commands:
if [ "$a" = "AC adapter : online" ] then echo "ONLINE" else echo "OFFLINE" fi
if [[ "$a" = "AC adapter : online" ]] then echo "ONLINE" else echo "OFFLINE" fi
With the [[ operator, you could drop the quotes around «$a» .
Why you got the error message
if $a -eq "AC adapter : online"
if AC adapter : online -eq "AC adapter : online"
which is a request to execute the command AC with the 5 arguments shown, and compare the exit status of the command with 0 (considering 0 — success — as true and anything non-zero as false). Clearly, you don’t have a command called AC on your system (which is not very surprising).
if grep -q -e 'some.complex*pattern' $files then echo The pattern was found in some of the files else echo The pattern was not found in any of the files fi
If you want to test strings, you have to use the test command or the [[ . ]] operator. The test command is the same as the [ command except that when the command name is [ , the last argument must be ] .
Convert array type variable to string type with space delimiter
If the first character of IFS variable is a space (which it is by default), you can use the star index in double quotes.
#! /bin/bash arr[0]=2019-06-26 arr[1]=15:21:54 string="$" printf "'%s'" "$string"
Documented under Special Parameters:
When the expansion occurs within double quotes, it expands to a single word with the value of each parameter separated by the first character of the IFS special variable.
For completeness, while the «$» Korn syntax (extended from the Bourne «$*» special parameter) would also work in zsh, in zsh, you may want to use the j (for join) parameter expansion flag instead which allows you to use any arbitrary joining string and doesn’t need to rely on a global parameter like $IFS :
Note that for «$» , ksh (both ksh93 and mksh) join on the first byte of $IFS instead of first character. That matters for multi-byte characters like:
$ ksh -c 'a=(foo bar); IFS="⇅"; echo "$"' foo�bar $ mksh -c 'a=(foo bar); IFS="⇅"; echo "$"' foo�bar $ mksh -o utf8-mode -c 'a=(foo bar); IFS="⇅"; echo "$"' foo�bar
(where that � is how my terminal emulator rendered the first byte (0xe2) of that ⇅ character which by itself doesn’t form a valid character).
Other Korn-like shells with array support are OK:
$ bash -c 'a=(foo bar); IFS="⇅"; echo "$"' foo⇅bar $ zsh -c 'a=(foo bar); IFS="⇅"; echo "$"' foo⇅bar $ yash -c 'a=(foo bar); IFS="⇅"; echo "$"' foo⇅bar
Convert array into string
I have a string say, test_var=ab_c_de_fg_.txt . I need to store ab_c in one variable (characters before the 2nd _ ) and de_fg_ in a second variable (characters after the second _ and before .txt ), so these two variables can be used in further operations.
test_var=ab_c_de_fg_.txt for ((i=0;i;i++)) do a[$i]="$" done flag=0 temp=0 while [["$temp" -le "$"]] do if a[temp] -eq "_" && flag -eq 0 flag = 1 continue fi if a[temp] -eq "_" && flag -eq 1 #var1=arr[0] to arr[$(temp-1)] #var2=arr[$(temp+1)] to arr[#(test_var)] fi temp=$((temp+1)) done
You mention an array, but there is no array here. And your code is full of errors, don’t you get error messages when you try to run this? What is that script supposed to be doing? It doesn’t seem to have any relation to what you describe in your question.
You already got some ready-made answers, but if you want to get that script or any other into even a remotely working condition, I’d suggest starting small, building it in pieces, and testing each piece before proceeding. Some useful that immediately came to mind: shellcheck.net and unix.stackexchange.com/questions/134472/… Also, fix the indentation. Having it messed up makes it really hard to read what the script is doing.
@terdon, the first loop would create an array made of the individual characters of the variable (if the missing $ was added before <#test_var>)#test_var>
@terdon, . and there’s the general idea of processing the string character-by-character, checking for the _ separator etc. Looks a bit like what someone might write in C to do that.
2 Answers 2
To split a string into an array, you can use the split+glob operator (invoked when you leave a parameter expansion unquoted in list context):
test_var=ab_c_de_fg_.txt root_name=$ # remove extension IFS=_ # split on _ set -o noglob # disable glob part array=( $root_name"" ) # split+glob, preserve empty trailing element if any
typeset -p array would then show something like:
typeset -a array=(ab c de fg '')
To join elements of an array with the first character (byte in ksh) of $IFS , you do «$» .
And your two variables could be defined like:
Here’s one way to do what your question asks for in bash (and ignoring your code, since I can’t understand what you’re trying to do with it):
$ test_var=ab_c_de_fg_.txt $ read var1 var2 < <(echo "$test_var" | sed 's/_/ /2; s/\.txt$//') $ echo "$var1" ab_c $ echo "$var2" de_fg_
In a script, that would just be:
test_var=ab_c_de_fg_.txt read var1 var2 < <(echo "$test_var" | sed 's/_/ /2; s/\.txt$//')
And you now have $var1 and $var2 .
The trick is using read to read the two variables. That will split its input on the current value of the environment variable IFS (which, by default, is a space a tab and a newline). The sed command will replace the 2nd _ with a space ( s/_/ /2 ) and remove the .txt from the end of its input ( s/\.txt$// ), so what is passed to read will be ab_c de_fg_.txt , and because there is a space in the middle, each string is saved in in the corresponding variable.