1

i need to store directory information in a way that i can parse as json.

when i do ls -m it gives me comma separated values but no user/group/size info.

bash-3.2$ ls -mp
100CANON/, 2009-11-27_1540.swf, 2009-11-27_1546.swf, 2009-11-27_1551.swf, 2009-11-30_0149.png, 429355_1.sql,
429355_1.sql.zip, About Stacks.pdf, Acrobat.com.app/

ls -l is problematic to parse.

is there anyway you know that I can get ls -l info as comma(or anything) separated values?

Devrim
  • 1,187
  • 3
    You should ask this on stackoverflow, because you need a function that returns data about files, rather than parsing ls.

    ls is designed to be human readable, and you can get the same data from a syscall.

    – Tom O'Connor Jan 09 '10 at 10:30
  • 1
    I respectfully disagree; as Joschi has clearly demonstrated. – Devrim Jan 09 '10 at 10:55
  • 3
    Why parse output of a command when the data is available in a more native format? – Tom O'Connor Jan 09 '10 at 13:28
  • Why comment when you have nothing to add ? – Devrim Jan 09 '10 at 23:21
  • I'm with Tom here. The commandline tool that Joschi suggests (and it is certainly a working solution) is just a front end to stat (2) and its siblings, so in a programming context you would usually prefer the the direct call rather than invoking a command line tool to convert the data to text which you then have to parse back to data. So, if this is a programming question, then SO would have been a better choice. – dmckee --- ex-moderator kitten Jan 09 '10 at 23:38
  • 1
    I don't mean to drag it but if i haven't mentioned JSON in my text, you wouldn't have your argument, thus you shouldn't use it. This question could have been "how to use stat to get comma separated values". Besides, clearly no programmer would know how to use stat command as well as a system admin would which is why this question is asked here. – Devrim Jan 11 '10 at 02:17
  • 1
    I think it is also impolite to imply "oh you'd do X if it is Y" this is as good as saying, why wouldn't one eat meat if hungry. Allergies? Diabetes? Religious? How could u dare to guess the conditions that this answer needs to fit? – Devrim Jan 11 '10 at 02:24

2 Answers2

5

You could use stat and define your own output format (see parameter -c).

Example:

$ stat -c '{"name": "%n", "size": "%s"}' *
{"name": "directory1", "size": "4096"}
{"name": "directory2", "size": "6"}
{"name": "file1", "size": "2070"}
{"name": "file2", "size": "83013"}
joschi
  • 21,665
1

just combine the ls -l output with some other commands, like this ls -l | tr ' ' ',' | tr '\n' ','. This way you should get the output you need.

Christian
  • 4,723