saketh
saketh

Reputation: 11

Create a json from given list of filenames in unix script

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

Upvotes: 0

Views: 1652

Answers (4)

Reino
Reino

Reputation: 3423

Very easy for the command-line tool and its integrated EXPath File Module:

$ xidel -se '
  array{
    for $x in file:list(.,false(),"*.txt")
    return {
      "filenumber":extract($x,"(\d+)\.txt",1),
      "name":$x
    }
  }
'

Upvotes: 1

Philippe
Philippe

Reputation: 26447

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:.})'

Upvotes: 1

saketh
saketh

Reputation: 11

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]'

Upvotes: 0

Hans-Martin Mosner
Hans-Martin Mosner

Reputation: 846

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.

Upvotes: 1

Related Questions