Moses
Moses

Reputation: 1273

Extract word and put it at the beginning of a line

I have json like this:

{"time_stamp":1397718404043,"request_id":"123456"}

I want to extract request_id and put it at the beginning of a line. For example:

123456 {"time_stamp":1397718404043,"request_id":"123456"}

Can I do it with sed or another unix tool? And how?

Upvotes: 1

Views: 112

Answers (6)

glenn jackman
glenn jackman

Reputation: 246807

bash:

json='{"time_stamp":1397718404043,"request_id":"123456"}'
{
    [[ $json =~ '"request_id":"'([^\"]+) ]] && echo -n "${BASH_REMATCH[1]} "
    echo "$json"
}
123456 {"time_stamp":1397718404043,"request_id":"123456"}

Upvotes: 0

Victor Henriquez
Victor Henriquez

Reputation: 1449

Another solution using perl:

s='{"time_stamp":1397718404043,"request_id":"123456"}' 
echo $s | perl -pe 'print /(\d+)"}/ , " "'
123456 {"time_stamp":1397718404043,"request_id":"123456"}

Upvotes: 2

Jotne
Jotne

Reputation: 41456

Just a simple extraction:

awk -F\" '{print $(NF-1),$0}'

echo '{"time_stamp":1397718404043,"request_id":"123456"}' | awk -F\" '{print $(NF-1),$0}'
123456 {"time_stamp":1397718404043,"request_id":"123456"}

Or just:

awk -F\" '$0=$(NF-1)OFS$0'

Upvotes: 0

Ed Morton
Ed Morton

Reputation: 203532

This will produce your posted desired output from your posted sample input:

$ sed 's/\(.*"\([^"]*\)".*\)/\2 \1/' file
123456 {"time_stamp":1397718404043,"request_id":"123456"}

If your actual input doesn't always follow the format you posted, update your question with more information and additional samples.

Upvotes: 4

Baba
Baba

Reputation: 850

you can use jq

echo '{"time_stamp":1397718404043,"request_id":"123456"}'|./jq ".request_id"

output is:

"123456"

see this page: http://stedolan.github.io/jq/manual/

update:

k='{"time_stamp":1397718404043,"request_id":"123456"}'
printf "%s %s\n" $(echo  $k|./jq ".request_id"|tr -d \")  $k

Upvotes: 3

anubhava
anubhava

Reputation: 785156

Using awk (not a dedicated json parser):

s='{"time_stamp":1397718404043,"request_id":"123456"}'
awk -F '"request_id" *: *"' '{p=$0; sub(/".*$/, "", $2); print $2, p}' <<< "$s"
123456 {"time_stamp":1397718404043,"request_id":"123456"}

Upvotes: 1

Related Questions