How to cut the first n and last n columns?

How can I disable the first n and last n columns from a tab delimited file?

I tried this to shorten the first column. But I'm not going to combine the first and last n columns

cut -f 1-10 -d "<CTR>v <TAB>" filename 
+51
linux bash shell
Feb 10 '11 at 12:08
source share
5 answers

Cutting can take several ranges in -f:

Columns up to 4 and from 7 to:

cut -f -4.7 -

or for fields 1,2,5,6 and from 10:

cut -f 1,2,5,6,10 -

etc.

+74
Feb 10 '11 at 12:36
source share

To use AWK to disable the first and last fields:

 awk '{$1 = ""; $NF = ""; print}' inputfile 

Unfortunately, this leaves field separators, so

 aaa bbb ccc 

becomes

 [space]bbb[space] 

To do this, use the kurumi answer, which will not leave extra spaces, but in a way that meets your requirements:

 awk '{delim = ""; for (i=2;i<=NF-1;i++) {printf delim "%s", $i; delim = OFS}; printf "\n"}' inputfile 

This also fixes a couple of issues in this answer.

To summarize this:

 awk -v skipstart=1 -v skipend=1 '{delim = ""; for (i=skipstart+1;i<=NF-skipend;i++) {printf delim "%s", $i; delim = OFS}; printf "\n"}' inputfile 

You can then change the number of fields to skip at the beginning or end by changing the variable assignments at the beginning of the command.

+2
Feb 10 '11 at 15:54
source share

You can use bash to do this:

 while read -a cols; do echo ${cols[@]:0:1} ${cols[@]:1,-1}; done < file.txt 
0
Apr 10 '16 at 2:51 on
source share

you can use awk, for example, disable 1st, 2nd and 3rd columns

 awk '{for(i=3;i<=NF-3;i++} print $i}' file 

if you have a programming language like Ruby (1.9+)

 $ ruby -F"\t" -ane 'print $F[2..-3].join("\t")' file 
-one
Feb 10 '11 at 12:13
source share

Try the following:

 echo a#b#c | awk -F"#" '{$1 = ""; $NF = ""; print}' OFS="" 
-one
Jan 24 '13 at 23:16
source share



All Articles