0

Have this peculiar requirement to print files in a given directory in the below mentioned format

filename1 <type of file> owner group
filename2 <type of file> owner group
$

The separator between columns being a tab.

I have been able to write the following command but the output of system command introduces a new line which I wish to avoid

find . -type f | xargs -I{} ls -let {} | awk -F" " 'BEGIN{OFS="\t" ORS=":"} {cmd=sprintf("file \"%s\"", $10);system(cmd);print $3,$4}'| tr -s ':\t ' '\t'

The produces the output as follows
filename1 <type of file>
owner group filename2 <type of file>
owner group $

I understand that the system command is reposnsible for the new line which I wish to avoid - I used ORS for the same reason but no luck.
Any help would be much appreciated.

2

You can use piped I/O from a command in awk (at least gawk, I haven't tested this on Solaris):

find . -type f | xargs ls -l | awk 'BEGIN { OFS="\t" } { command=sprintf("file \"%s\"", $9); command | getline type; close(command); print type, $3, $4 }' | tr ":" "\t"

If your find supports it you can simplify this with

find . -type f -ls | awk ...

There's a handy resource on using getline which covers a number of caveats (including not using close() as I had initially).

5
  • Worked like a charm. Thanks for the great tip using readline. – Prasoon May 6 '15 at 8:57
  • Wanted to know, is there a way I can perform an if condition analysis on the output of the file command above? Say, if the file output says that the file is an ELF executable, can I run ldd and display the output alongside? – Prasoon May 11 '15 at 4:56
  • If you have another question you should really ask a new question. Nevertheless, you can use type in the same way as any other variable, in particular in an if condition after getline (... getline type; if (type ...) { ... }; print type, $3, $4). Try it and see... – Stephen Kitt May 11 '15 at 5:11
  • Realized that after running the original command you gave, without using close, I run into instances of "awk: line 0 (NR=252): too many open streams to getline onto "file "some filename here"" kind of issue. – Prasoon May 11 '15 at 8:06
  • Indeed, I'll update my answer. – Stephen Kitt May 11 '15 at 8:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.