Cut and Paste

Cutting and Pasting Text

Cut Command Examples


The cut command enables you to extract a column of columns of information from a file. To specify the column that is to be extracted, we use the -c parameter. This is then followed by the column number. To extract more than one column, a comma separated list can be passed. Fields may also be specified by using the -f. A delimiter may also be specified with the -d parameter. The default delimiter is the tab character unless specified.




john@john-desktop:~/test_examples$ cat cutfile1.txt
harry,25,16200
gill,46,17500
bill,45,20000
john,43,100000
barry,27,42000
paul,18,26500
john@john-desktop:~/test_examples$ cut -d, -f 1,3 cutfile1.txt
harry,16200
gill,17500
bill,20000
john,100000
barry,42000
paul,26500

In the above example we have specified a delimiter of ",". We are specifying fields 1 and 3 are to be cut in the file "cutfile1.txt".



john@john-desktop:~/test_examples$ cat cutfile1.txt
harry,25,16200
gill,46,17500
bill,45,20000
john,43,100000
barry,27,42000
paul,18,26500
john@john-desktop:~/test_examples$ cut -c 1-4 cutfile1.txt
harr
gill
bill
john
barr
paul

The above is an example of the cut command in its simplest form. Here we are cutting the first 4 letters from the file "cutfile1.txt".



Paste Command Examples


The paste command is useful for merging files together. The first line of each file is joined separated by a Tab character. It is possible to specify a different delimiter with the -d parameter.



john@john-desktop:~/test_examples$ cat pastefile1.txt
one
two
three
four
five
john@john-desktop:~/test_examples$ cat pastefile2.txt
six
seven
eight
nine
ten
john@john-desktop:~/test_examples$ paste pastefile1.txt pastefile2.txt
one	six
two	seven
three	eight
four	nine
five	ten

The next example is the same, however, we have changed the default Tab delimiter to a ":



john@john-desktop:~/test_examples$ cat pastefile1.txt
one
two
three
four
five
john@john-desktop:~/test_examples$ cat pastefile2.txt
six
seven
eight
nine
ten
john@john-desktop:~/test_examples$ paste -d: pastefile1.txt pastefile2.txt
one:six
two:seven
three:eight
four:nine
five:ten