[plug] A bit of gross bash code
Bill Cullen
billc at iinet.net.au
Wed Mar 7 21:20:34 WST 2001
Brad Campbell wrote:
>
> Ok, I'm sure you have had enough of me today, but here is a bit
> of bash code I wrote to solve a problem..
> Question is, is there an easier way to do this.. or am I on the right
> track. I mean, it works, but it's very rough.
> As you can see, I'm pretty new to the bash scripting arena, but I can
> read man pages :p)
>
> it takes an ls -la /dev
>
> crw--w--w- 1 0 5 29, 28 Feb 23 1999 fbuser4
> crw--w--w- 1 0 5 29, 29 Feb 23 1999 fbuser5
> crw--w--w- 1 0 5 29, 30 Feb 23 1999 fbuser6
> crw--w--w- 1 0 5 29, 31 Feb 23 1999 fbuser7
> lrwxrwxrwx 1 0 0 13 Apr 14 2000 fd -> /proc/self/fd
> brw-rw---- 1 0 25 2, 0 Feb 9 2000 fd0
> brw-rw---- 1 0 25 2, 84 Feb 9 2000 fd0u1040
> brw-rw---- 1 0 25 2, 88 Feb 9 2000 fd0u1120
> brw-rw---- 1 0 25 2, 28 Feb 9 2000 fd0u1440
> brw-rw---- 1 0 25 2, 124 Feb 9 2000 fd0u1600
>
> and generates an : delimited file for me to parse later
>
> c:0:5:29:28:fbuser4
> c:0:5:29:29:fbuser5
>
> You get the idea.. it does this for types c,u & b
>
How about a script using awk:
ls -ln /dev | awk '
/^[bcu]/ { Type=substr($1,1,1)
printf("%s:%s:%s:",substr($1,1,1),$3,$4)
printf("%s:%s:",substr($5,1,length($5)-1),$6)
# now print all the fields from field 10 on
# ie if the filename has spaces we will have
# more than 10 fields
for (i=10 ; i <= NF ; i++ ) {
printf("%s",$i)
if ( i < NF )
printf(" ")
else
printf("\n")
}
}'
or one without awk:
ls -ln /dev | grep "^[bcu]" | while read Perms Links Owner Group \
Major Minor Month Day YearOrTime FileName
do
echo -n `echo ${Perms} | cut -c1-1`
echo -n ":${Owner}:${Group}:"
echo -n `echo ${Major} | tr -d ','`
echo ":${Minor}:${FileName}"
done
Note that both of these scripts will handle files with spaces
in their names (or any other characters for that matter, although
I've only tested for spaces). Note that the solution using grep
won't convert double spaces to single spaces (ie. file name will
be displayed as file name).
I could have combined all the echos into one line of course,
but I think that might have detracted from the readability.
Bill
--
---------------------------------------------------------------------
Bill Cullen, ENFP, billc at wantree.com.au, Perth, Western Australia
Life's too important to take seriously.
=====================================================================
More information about the plug
mailing list