1

I have a file with millions of rows and want to modify values in column A only if the string is '.'. The modification would be to add "chr:"$2":"$3 to the start of the string. All other rows would be printed as the original version.

Example Input:

A B C D E F G H
rs125 2 5433 T TACA A 3 2
chr2:4543 2 4543 I R 8 2
rs123 3 4332 A C 9 3
. 3 7654 I R 8

Above, the 4th row begins with '.' and needs to be changed to 'chr3:7654'. All other rows need to remain unchanged.

Desired Output:

A B C D E F G H
rs125 2 5433 T TACA A 3 2
chr2:4543 2 4543 I R 8 2
rs123 3 4332 A C 9 3
chr3:7654 3 7654 I R 8 2

My code so far works but changes ALL names to begin 'chr...' even when 'rs...' should remain unchanged:

awk '($1 ~ /^./) {$1 = "chr:"$2":"$3}1' filename > newfilename

It is probably a very simple solution but it is causing very big problems. Thanks!

  • 2
    The period (.) is a metacharacter in regex (which I'm assuming awk is using here). Try escaping it (\.). – Tom Hunt Sep 17 '15 at 15:17
3

Your problem is the regex. /^./ will match any valid character at start of line. You must escape . to match it literally:

awk '$1 ~ /^\./ {$1 = "chr:"$2":"$3};1' filename > newfilename

But it's better to just check for string equal instead of doing regex checking:

awk '$1 == "." {$1 = "chr:"$2":"$3};1' filename > newfilename
  • I used the second option of string equal and seems to work perfectly. Thanks @cuonglm – Bob Sep 17 '15 at 15:27

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.