Home > OS >  Create a json from given list of filenames in unix script
Create a json from given list of filenames in unix script

Time:09-28

Hello I am trying to write unix script/command where I have to list out all filenames from given directory with filename format string-{number}.txt(eg: filename-1.txt,filename-2.txt) from which I have to form a json object. any pointers would be helpful.

 [{
        "filenumber": "1",
        "name": "filename-1.txt"
    },
    {
        "filenumber": "2",
        "name": "filename-2.txt"
    }
 ]

In the above json file-number should be read from {number} format of the each filename

CodePudding user response:

A single call to jq should suffice :

shopt -s extglob
printf "%s\0" *- ([0-9]).txt | \
    jq -sR 'split("\u0000") |
            map({filenumber:capture(".*-(?<n>.*)\\.txt").n,
                 name:.})'

CodePudding user response:

Intuitively, I'd say you can do this with jq. However, in practice I've rarely been able to achieve what I wanted with jq :-)

With some lunch break puzzling, I've come up with this beauty:

ls | jq -R '{filenumber:input_line_number, name:.}' | jq -s .

Instead of ls you could use any other command that produces a newline separated list of strings.

CodePudding user response:

I have tried with multiple examples to achieve exact use case of mine and finally found this working fine exactly how I wanted Thanks

 for file in $(ls *.txt); do file_version=$(echo $file | sed 's/\(^.*-\)\(.*\)\(.txt.*$\)/\2/'); jq -n --arg name "$file_version" --arg path "$file" '{name: $name, name: $path}'; done | jq -n '.urls |= [inputs]'
  • Related