I have loads of geographical json files with date_geohash.json
name format and I have to convert them to date_latitude-longotude.json
format. For example I need to convert 2017-03-28_u13hhyn.json
to 2017-03-28_N52.76-E1.62.json
.
I’m trying to write a bash script to rename these json files using ‘rename’ and ‘jq’ (json query) utilities. Using jq I can extract latitude and longitude from the json files.
jq '"(.latitude)-(.longitude).json"' 2017-03-28_u13hhyn.json
gives me
“52.768471-1.623297.json"
However, I don’t know how to truncate the latitude and longitude digits and rename the json files.
Advertisement
Answer
It might be better to extract the latitude and longitude into variables, then manipulate into the filename format you want with printf. Then just rename the file. Here’s a basic example:
#!/bin/bash declare directory="/some/directory/path" declare pattern="*_*.json" cd ${directory} for file in ${pattern}; do prefix=${file%%_*} # Remove first underscore and everything following. latitude=$(jq '.latitude' ${file}) longitude=$(jq '.longitude' ${file}) new_name=$(printf "%s_N%.2f-E%.2f.json" ${prefix} ${latitude} ${longitude}) mv ${file} ${new_name} done;
Note 1: printf does not truncate the numbers, it rounds them, which is going to give more accurate results.
Note 2: I have hard-coded ‘N’ and ‘E’ into the filename, on the assumption that latitude and longitude will be negative for S and W. If this is not the case, there is a little more work required, but the priciple stays the same.