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)
111 222 3333 444 555 666
111 222 3333 444 555 666
111 222 3333 444 555 666
111 222 3333 444 555 666
111 222 3333 444 555 666
Command
cut -f1,4,6 filename
Output
111 444 666
111 444 666
111 444 666
111 444 666
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)
111 222 3333 444 555 666
111 222 3333 444 555 666
111 222 3333 444 555 666
111 222 3333 444 555 666
111 222 3333 444 555 666
Command
cut -c9,16 filename
Output
222
222
222
222
222