6

I need to write a script that would "cut" the output of the id command into three parts. For example:

Let's say id gives this output: uid=12345(mylogin) gid=100(users)

And my script should output it like this:

Login: mylogin
Id: 12345
Group: users
9

Using multiple character field separator in awk

$ echo 'uid=12345(mylogin) gid=100(users)' | awk -F'[=()]' '{print "Login: " $3 "\nId: " $2 "\nGroup: " $6}'
Login: mylogin
Id: 12345
Group: users
  • -F'[=()]' set = or ( or ) as field separators
  • $3 will be third field, after first = and the first ( terminated by ). So it gets the value mylogin
  • Similarly for other fields and print as required
  • Thank you. This task was placed under "awk" command paragraph in my learning material so I will accept this answer as the correct one. – Deividas Mar 26 '17 at 14:17
17

Don't bother trying to parse it. POSIX requires that id support various options to do this automatically:

printf "Login: %s\nId: %s\nGroup: %s\n" "$(id -un)" "$(id -u)" "$(id -gn)"

In addition to being more work, parsing is complicated by the fact that id with no options is permitted to produce locale-dependent output:

The following formats shall be used when the LC_MESSAGES locale category specifies the POSIX locale. In other locales, the strings uid, gid, euid, egid, and groups may be replaced with more appropriate strings corresponding to the locale.

While most reasonable parsing tools can cope with this, anything that isn't Unicode-aware may have problems.

8

One way can be:

# 0 |  1  |   2   |  3 | 4 |  5  |
#uid=12345(mylogin) gid=100(users)
IFS='(=)' read -a A <<<"$(id)"
printf '%s: %s\n' Login "${A[2]}" Id "${A[1]}" Group "${A[5]}"
# remember array A indexing begins at 0.
4

Literally, using only cut:

echo Login: $(id | cut -d ' ' -f1 | cut -d= -f2 | cut -d '(' -f1)
echo Id: $(id | cut -d ' ' -f1 | cut -d= -f2 | cut -d '(' -f2 | cut -d  ')' -f1)
echo Group: $(id | cut -d ' ' -f2 | cut -d '(' -f2 | cut -d ')' -f1)

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.