3

I have a big file in this format, whose first few lines I am showing you including the header.

gene    c1  c2  c3  c4  c5  c6  c7  c8
G1*1    0   0   0   0   0   0   0   0
G2*2    0   0   0   0   1   1   1   1
G3*3    0   0   2   2   44  44  62  62
G4*4    22  0   46  0   1308    7   1773    4

First line with the gene is the header line. I want to keep it as it is and then I want to split the remaining line with FS = *, so that now I have a file looking like this as output

gene    coord   c1  c2  c3  c4  c5  c6  c7  c8
G1  1   0   0   0   0   0   0   0   0
G2  2   0   0   0   0   1   1   1   1
G3  3   0   0   2   2   44  44  62  62
G4  4   22  0   46  0   1308    7   1773    4

So also I want to place an extra field in the header line named 'coord', so that when i split the subsequent lines I have everything ordered.

I know how to use awk for splitting but header line is what is confusing me

awk -F '*' -v OFS="\t" '{print $1,$2}' ##This is for 2nd line and onwards
5

The header line is a special case, so you can handle it as a special case.

awk -F '*' -v OFS='\t' \
  'NR == 1 { sub(/^gene/, "&" OFS "coord"); print; next }
  { print $1, $2 }'
  • Can you explain what is OFS doing in sub part?? – user3138373 Dec 17 '14 at 17:02
  • @user3138373 It's just a tab to separate gene and coord into separate columns. – jw013 Dec 17 '14 at 17:39
4

Is the use of awk an absolute requirement?  This seems more like a job for sed:

sed '1s/gene/&    coord/;2,$s/\*/  /'

which is just about self-explanatory:

  • 1s/gene/& coord/ – on the first line, change “gene” to “gene    coord”.
  • 2,$s/\*/ / – on the second line through the end of the file, change literal “*” to white space.
4

Here is another approach:

awk -F '[ \t*]' -v OFS='\t' 'NR==1{$2="coord\t"$2;print;next}{$1=$1}1' file
  • The input file wasn't clear for me, so I used 3 field separators: space, tab, and *. You can probably remove something from the list if you now your input better.

  • $1=$1 basically does nothing, it is needed to reorganize fields (use new field separator everywhere)

  • final 1 is used just to print everything after modification.

  • Hi can you explain the code with [\t*] I think you are spiltting on 2 delimiters tab and *. Can you explain $1=$1 and 1 thing? – user3138373 Dec 17 '14 at 16:58
  • @user3138373 Your input file wasn't clear for me, so I used 3 field separators: space, tab, and star. You can probably remove something from the list if you now your input better. $1=$1 basically does nothing, it is needed to reorganize fields (use new field separator, a tab, everywhere), and last 1 is used to just print everything. – jimmij Dec 17 '14 at 17:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.