Search code examples
bashcut

Using cut command to remove multiple columns


given input

 echo 1,2,3,4,5,6,7,8,9,...100 

If I want to cut columns 5 I can do

cut -d, -f-4,6-

what if I want to cut multiple non consecutive columns like 5, 7,etc is there a one liner?


Solution

  • You should be able to continue the sequences directly in your existing -f specification.

    To skip both 5 and 7, try:

    cut -d, -f-4,6-6,8-
    

    As you're skipping a single sequential column, this can also be written as:

    cut -d, -f-4,6,8-
    

    To keep it going, if you wanted to skip 5, 7, and 11, you would use:

    cut -d, -f-4,6-6,8-10,12-
    

    To put it into a more-clear perspective, it is easier to visualize when you use starting/ending columns which go on the beginning/end of the sequence list, respectively. For instance, the following will print columns 2 through 20, skipping columns 5 and 11:

    cut -d, -f2-4,6-10,12-20
    

    So, this will print "2 through 4", skip 5, "6 through 10", skip 11, and then "12 through 20".