Reputation: 615
Let's say I have firstJSON.json secondJSON.json ...
under the same folder, and each file looks like
{
"obj1":"item1",
"obj2":"item2"
}
Now I want to strip item1
and item2
, then put them into one file outFile
, I have written the following code to do that:
function strip {
item1=$(cat $1 | grep 'obj1' | cut -d '"' -f4)
item2=$(cat $1 | grep 'obj2' | cut -d '"' -f4)
name=$(echo $1 | cut -d '.' -f1)
echo $name':'$item1':'$item2 >> ./outFile
}
but how do I use this piece of code to strip info from every JSON file and then put them all into outFile
?
Upvotes: 0
Views: 84
Reputation: 827
A single grep on all files is enough piped into an awk munger
files=$*
grep -HPo '^ +"obj\d+" *: *"\K[^"]+' $files|
awk -F: '
src == $1 {
printf(":%s", $2)
next
}
{
if(src) printf("\n")
src=$1
f1=gensub(/\.[^.]*$/,"",1,$1)
printf("%s:%s", f1, $2)
}
END {printf("\n")}
'
Upvotes: 1
Reputation: 4112
you can use with for loop as below;
for j in *.json; do
item1=$(cat $j | grep 'obj1' | cut -d '"' -f4)
item2=$(cat $j | grep 'obj2' | cut -d '"' -f4)
name=$(echo $j | cut -d '.' -f1)
echo $name':'$item1':'$item2 >> ./outFile
done
Upvotes: 0