0

Here is my JSON:

{"login":"WG1118412764OA","password":"9Hv1zd74nKhYovZa"}

I have very basic grep, no Python, no Perl, and no jq obviously, just awk and sed.

Could somebody give me a hand on that?

I need to have login and password values as shell variables.

Thanks

Kal800

1

3 Answers 3

3

Alternative to cut if you want builtin tools only ;-)

OLD_IFS="$IFS"
IFS='"'
set -- $(<file)
IFS="$OLD_IFS"

login=$4
password=$8

or even:

IFS='"' read -r a b c login d e f password g < file

Note, that a slight change of your input json or a " inside the password would be an issue.

Better use a proper json parser e.g. jq. And if you don't have that, install it or let an admin install it for you. Always have the right tools for your tasks!

0
2

Assuming you have all of the mandatory POSIX tools, not just awk, sed, and grep, you could just use cut for input such as you show:

$ login=$(cut -d'"' -f4 file)
$ passwd=$(cut -d'"' -f8 file)
$ echo "$login"
WG1118412764OA
$ echo "$passwd"
9Hv1zd74nKhYovZa

If that's not all you need then edit your question to provide more truly representative sample input/output including cases that doesn't work for.

10
  • 2
    You're welcome. Give it some time to see if you get a better answer and then see unix.stackexchange.com/help/someone-answers for what to do next.
    – Ed Morton
    Jun 1 at 14:02
  • 1
    @Kal800 can you be certain you will never have " in the password?
    – terdon
    Jun 1 at 14:03
  • 5
    Then why do you create a json if you don't have the tools to parse it properly and not a shell script that you can just source, e.g. login=...; password=... ?
    – pLumo
    Jun 1 at 14:16
  • 1
    @Kal800 It seems rather strange to create a JSON document from some data, only to parse the data out from the JSON document, especially if you don't have any sensible JSON parsing tools at hand. What is the sense of creating the JSON document in the first place?
    – Kusalananda
    Jun 1 at 15:05
  • 1
    That API serves different purposes and different recipients are involved. One of them is small OpenWrt router that has to get this data but does not have the tools which other devices in the environment have.
    – Kal800
    Jun 1 at 15:10
1

In a comment, it is mentioned that the system this task is to be performed on is an OpenWrt router. Since jq is available for OpenWrt, it seems like a good idea to use it to extract the wanted data:

eval "$(jq -r '"login=\(.login|@sh); password=\(.password|@sh)"' file)"

This uses jq to create two shell assignments. When evaluated, the assignments assign the decoded and quoted username and password to the two shell variables login and password.

Or, if you want to parse the file twice:

login=$(jq -r '.login' file)
password=$(jq -r '.password' file)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.