Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash Script : Printing a column with having space between the string

Tags:

bash

shell

sed

awk

I have run into the the wall with this problem. When i Run ls -l command. I get this result ( I intentionally omitted the columns after 5th below for simplicity)

-rw-r--r--. 1 leslie users Aug 26 00:14
-rw-r--r--. 1 sherri root Aug 26 00:14
-rw-r--r--. 1 marie domain users Aug 26 00:14

I want to print the Group Ownership Column. through several ways i can print 4th Column which is group ownership column . The problem is some group names have space in it .For example :- "domain users" . ls -l | awk '{print $4}' is Printing 4th column like this

users
root
domain

The output i want is

users
root
domain users

PLease help. I am stuck here from many days. i really need some intelligent mechanism which can detect that domain users or other groups with space name is a group name which falls under the group ownershi category. My groups are coming from Active Directory . that's why some have space in it.

like image 896
Rose Avatar asked Feb 28 '26 23:02

Rose


1 Answers

You are parsing the output of ls. Don't do that. For some of the reasons why see: Why you shouldn't parse the output of ls(1)

As an alternative, try GNU find. This will print group names:

find . -maxdepth 1 -printf '%g\n'

If you want the file name displayed before the group name:

find . -maxdepth 1 -printf '%-20f %g\n'

Finding the unique group names

The output of the above can be sent to sort -u to select only the unique names:

find / -path /proc -prune -o -printf '%g\n' | sort -u
like image 161
John1024 Avatar answered Mar 03 '26 17:03

John1024



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!