Shell Scripting

Sunday, February 1, 2015

Cut command R and D

Below is the content from a file called Userlist
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
apache:x:48:48:Apache:/var/www:/sbin/nologin
dovecot:x:97:97:dovecot:/usr/libexec/dovecot:/sbin/nologin
nfsnobody:x:65534:65534:Anonymous NFS User:/var/lib/nfs:/sbin/nologin
avahi-autoipd:x:100:156:avahi-autoipd:/var/lib/avahi-autoipd:/sbin/nologin
daniel:x:86:86:Sabayon user:/home/sabayon:/sbin/nologin
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1. Select Column of Characters using Range
----------------------------------------
Range of characters can also be extracted from a file by specifying start and end position delimited with -. The following example extracts first 3 characters of each line from a file called userlist

bash-3.2$ cut -c1-3 userlist
apa
dov
nfs
ava
dan
------------------------------------------
Note: If you like to extract a some part of the output, you can combine option -f and -d. The option -f specifies which field you want to display, and the option -d specifies what is the field delimiter you are going to use to display the desired output

2. Select Column of Characters using either Start or End Position

Either start position or end position can be passed to cut command with -c option.
The following specifies only the start position before the ‘-’. This example extracts from 2nd character to end of each line from userlist file.

bash-3.2$ cut -c2- userlist
pache:x:48:48:Apache:/var/www:/sbin/nologin
ovecot:x:97:97:dovecot:/usr/libexec/dovecot:/sbin/nologin
fsnobody:x:65534:65534:Anonymous NFS User:/var/lib/nfs:/sbin/nologin
vahi-autoipd:x:100:156:avahi-autoipd:/var/lib/avahi-autoipd:/sbin/nologin
aniel:x:86:86:Sabayon user:/home/sabayon:/sbin/nologin
-----------------------------------------------
3. Select a multiple Fields from a File

You can also extract more than one fields from a file or stdout. Below example displays username and home directory of users who has the login shell as “/sbin/nologin”.

bash-3.2$ grep "/sbin/nologin" userlist | cut -d':' -f1,6
apache:/var/www
dovecot:/usr/libexec/dovecot
nfsnobody:/var/lib/nfs
avahi-autoipd:/var/lib/avahi-autoipd
daniel:/home/sabayon
--------------------------------------------------

No comments:

Post a Comment