74

I have bunch of files sitting in folders like

data\A\A\A\json1.json
data\A\A\A\json2.json
data\A\A\B\json1.json
...
data\Z\Z\Z\json_x.json

I want to cat all the jsons into one single file?

2240
  • 1,547
  • 2
  • 12
  • 30
frazman
  • 32,081
  • 75
  • 184
  • 269

4 Answers4

124
find data/ -name '*.json' -exec cat {} \; > uber.json

a short explanation:

find <where> \
  -name <file_name_pattern> \
  -exec <run_cmd_on_every_hit> {} \; \
    > <where_to_store>
Pavel
  • 7,436
  • 2
  • 29
  • 42
18

Use find to get all the JSON files and concatenate them.

find data -name '*.json' -exec cat {} + > all.json

Note that this will not be valid JSON. If you want a JSON file to contain multiple objects, they need to be in a containing array or object, so you'd need to add [ ] around them and put , between each one.

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • 3
    Strictly true, but it would be quite perverse to have directories with `.json` extensions. – Barmar Apr 14 '15 at 08:39
  • How do you add the ',' chars in the command above between each file? – Gal Bracha Nov 09 '17 at 20:01
  • 1
    @GalBracha Use a `find` command that just prints the filenames, pipe that to a script that reads each filename, does `cat "$filename"; echo ','`. – Barmar Nov 09 '17 at 20:47
  • 1
    You'll then have to edit the file when done to remove the last `,` – Barmar Nov 09 '17 at 20:48
  • @rwitzel If you end the `-exec` option with `+` instead of `;` it replaces `{}` with all the filenames instead of running the command separately for each filename. – Barmar Apr 12 '19 at 17:58
11

Alternatively -- if you have a list of your files -- you can pipe that to xargs

<path to your files> | xargs cat > all.json
csiu
  • 3,159
  • 2
  • 24
  • 26
9
find ./ -type f | xargs cat > ../singlefilename

I would like this ,easy and simple.

../ avoid the error input file is output file.

danius
  • 2,664
  • 27
  • 33
LuciferJack
  • 781
  • 11
  • 12