How do I extract certain columns from a text file in Unix?
Somehow I can never remember the cut command in Unix. But I occasionally want to remove certain columns from a text file of data. cut will do that.
Delimited
Here is a simple tab-delimited example. (Use the -d option to set a different column delimiter.)
Data File (tab-delimited)
xxxxxxxxxx
1
2
111 222 3333 444 555 666
3
111 222 3333 444 555 666
4
111 222 3333 444 555 666
5
111 222 3333 444 555 666
6
111 222 3333 444 555 666
Command
xxxxxxxxxx
1
2
cut -f1,4,6 filename
Output
xxxxxxxxxx
1
2
111 444 666
3
111 444 666
4
111 444 666
5
111 444 666
6
111 444 666
There are two other examples in the Search and Replace section of this KB article.
https://kb.ucla.edu/link/117
More options are available in the Unix man pages for cut. Type man cut
Fixed Width
Use the -c option to select characters based on position.
Data File (fixed width)
xxxxxxxxxx
1
2
111 222 3333 444 555 666
3
111 222 3333 444 555 666
4
111 222 3333 444 555 666
5
111 222 3333 444 555 666
6
111 222 3333 444 555 666
Command
xxxxxxxxxx
1
2
cut -c9,16 filename
Output
xxxxxxxxxx
1
2
222
3
222
4
222
5
222
6
222