1

I have created a 0,1,2 genotype matrix and I want to replace all of the -1 with 9.

0   0   -1  0   0   0   0   2   0   0   0   0   -1
0   0   1   0   0   0   0   0   0   0   0   -1   1
0   0   2   0   0   -1  2   0   0   0   -1  0    0

I tried this:

sed -ie 's/^[-1] /9 /' file1 > file2

but it seems that it does not work.

Is there any way to do that?

  • 2
    The [] enclose a collection of characters, so each occurrence of either - or 1 matches, but the ^ anchors the expression to the beginning of the line, so you don't get any match. You also miss the g flag to handle multiple occurences in a line. – Philippos Aug 3 '17 at 7:08
2
sed 's/-1/9/g' file > file2
  • Place a space behind the 9 or you'll break the columns. – Philippos Aug 3 '17 at 7:09
1
sed -i 's/-1/9 /g' file
sed 's/-1/9 /g' file1 > file2
0

To do it in safe manner:

sed -e '
   s/$/ /
   :a;s/ -1 / 9 /;ta
   s/.$//
' file1

where

  • s/$/ / insert a space at end of line
  • :a;s/ -1 / 9 /;ta do substitution (space is needed if -1 at end of line)
  • s/.$// remove space from end of line
-2

I found the answer

sed -E 's/[-1] / 9/' file1 > file2

can do the job

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.