shellscript get column data
I have a file that's the result of the comm comma开发者_JAVA技巧nd, it has 2 columns, I wish to separate these 2 columns into two different files, how do I do that?
the file looks like:a b g f c d
Depending on the column separator, you can do something like:
cut -f1 orig_file >file1
cut -f2 orig_file >file2
Here the column separator is supposed to be a TAB. If it is another character, you can use the -d char
option to cut
.
If you want to remove empty lines, as per your request, you can add to each line a sed
command:
cut -f1 orig_file | sed -e /^$/d >file1
cut -f2 orig_file | sed -e /^$/d >file2
You can cut the relevant parts based on character indexes:
# assuming constant 5 chars for col1, 5 chars for col2
cat file | cut -c0-5 | sed '/^\s*$/ {d}' > col1
cat file | cut -c6-10 | sed '/^\s*$/ {d}' > col2
The sed
pipe removes empty lines (those with only whitespace). They can also be removed with grep -v '^[[:space:]]*$'
.
Using cut
will result in a command for each and every column.
You can do it using awk in a single command.
awk '{for (i=1;i<=NF;i++) print $i>i".txt"}' your_file
By default Tab is the field separator.
Incase the field separator is other than tab,then add a flag after awk
like below
awk -F"<field separator>" '{....
精彩评论