user14645176
user14645176

Reputation:

Pipe data from multiple files into their original files

I'm trying to read data from JSON files, compact them, and then output them back into their original files, but I'm not having much luck. The files are spread out across directories and I'm running the find command in the root directory.

The command looks like this:

find . -name '*.json' -exec cat {} \; | jq -c '.'

Upvotes: 1

Views: 382

Answers (1)

LMC
LMC

Reputation: 12777

Sending findoutput to a while loop to handle found files and using this answer could achieve what you expect. Make a backup of your files since they will be overwritten.

#!/bin/bash
function rewrite() {
    local rfile="$1"
    echo "func : $rfile"
    local contents=$(< "$rfile")
    cat <<< "$contents" | jq -c '.' > "$rfile"
}
while read fjson ;do
    echo "$fjson"
    rewrite "$fjson"
done  < <(find $HOME/tmp -name '*.json')

Upvotes: 1

Related Questions