Wednesday 31 July 2019

Linux - cut command useful examples

cut is a command from coreutility which allows you to print selected parts of lines from each FILE to standard output.
Here is an output from lscpu -p option, it will be used in examples below as testfile
# Socket,CPU,Core,Address,Online,Configured,Polarization
0,0,0,,Y,,
0,1,1,,Y,,
0,2,2,,Y,,
0,3,3,,Y,,
0,4,4,,Y,,
0,5,5,,Y,,
1,6,6,,Y,,
1,7,7,,Y,,
1,8,8,,Y,,
1,9,9,,Y,,
1,10,10,,Y,,
1,11,11,,Y,,

Example 1: print one specified field(second field in below example)

# cut -d',' -f2 testfile
CPU
0
1
2
3
...
Option -d and -f
       -d, --delimiter=DELIM
              use DELIM instead of TAB for field delimiter
       -f, --fields=LIST
              select only these fields;  also print any line that contains no delimiter character, unless the -s option is specified

Example 2: print two fields

# cut -d',' -f2,5 testfile
CPU,Online
0,Y
1,Y
2,Y
...

Example 3: print a range of fields

# cut -d',' -f2-5 testfile
CPU,Core,Address,Online
0,0,,Y
1,1,,Y
...

Example 4: print a range of fields, from specified field to rest

# cut -d',' -f2- testfile
CPU,Core,Address,Online,Configured,Polarization
0,0,,Y,,
1,1,,Y,,
...

Example 5: print a range of fields, the first to the specified one

# cut -d',' -f-2 testfile
# Socket,CPU
0,0
0,1
...

Same rule applys to -b and -c

-b and -c
       -b, --bytes=LIST
              select only these bytes
       -c, --characters=LIST
              select only these characters
# cut -c1 testfile
#
0
...

# cut -c1,5 testfile
#c
00
...

# cut -c1-5 testfile
# Soc
0,0,0
...

# cut -c-5 testfile
# Soc
0,0,0
...
# cut -c5- testfile
cket,CPU,Core,Address,Online,Configured,Polarization
0,,Y,,
1,,Y,,
...

More options

       -n     with -b: don't split multi byte characters
       --complement
              complement the set of selected bytes, characters or fields
       -s, --only-delimited
              do not print lines not containing delimiters
       --output-delimiter=STRING
              use STRING as the output delimiter the default is to use the input delimiter

0 comments:

Post a Comment