jsonlinuxshellunixcommand-line

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


Solution

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