Pages

Sunday, May 8, 2016

cut command one liners


To get only second character using position number

# cut -c2 test.txt

To get set of characters using position number range

# cut -c1-3 test.txt

To get all characters starting from second character till end of line using position number

# cut -c2- test.txt

To get all characters from start of line till till tenth character using position number

# cut -c-10 test.txt

To get only first field of each line from /etc/passwd file using the field delimiter : (colon)

# cut -d':' -f1 /etc/passwd

To get multiple fields of each line from /etc/passwd file using the field delimiter : (colon)

# grep "/bin/bash" /etc/passwd | cut -d':' -f1,6

To get first 4 and 6th, 7th fields of each line from /etc/passwd file using the field delimiter : (colon)

# grep "/bin/bash" /etc/passwd | cut -d':' -f1-4,6,7
To get first field of lines which contain the delimiter, i.e. in /etc/passwd example, if you pass a different delimiter other than : (colon), cut will just display the whole line containing that delimiter.

# grep "/bin/bash" /etc/passwd | cut -d'n'  -f1

To get fields except the specified fields option --complement is used

# grep "/bin/bash" /etc/passwd | cut -d':' --complement -s -f7

To change output delimiter for display (change : to #)

# grep "/bin/bash" /etc/passwd | cut -d':'  -s -f1,6,7 --output-delimiter='#'

To change output delimiter for display (change : to newline)

# grep "/bin/bash" /etc/passwd | cut -d':'  -f1,6,7 --output-delimiter=$'\n'

No comments:

Post a Comment