8

I have a text file named xid.txt:

xid: SC48028 id: artf398444
xid: indv1000 id: indv24519
xid: SC32173 id: artf398402
xid: SC21033 id: artf398372
xid: 1001 id: tracker4868
xid: wiki1000 id: wiki10709
xid: proj1234 id: proj12556

I need to add a string 'PT_' before 'SC48028' , 'SC32173' ... so on. The string 'SC...' can start with any combination may be 'AC...' or 'DL..'

Required output:

xid: PT_SC48028 id: artf398444
xid: indv1000 id: indv24519
xid: PT_SC32173 id: artf398402
xid: PT_SC21033 id: artf398372
xid: 1001 id: tracker4868
xid: wiki1000 id: wiki10709
xid: proj1234 id: proj12556

If you see the above output, we should not insert 'PT_' before strings which start with 'i' , 'p' , 'w' & 'numerical' . I have tried a few basic commands for my requirement using insert/append in sed.

  • 2
    Your question is on topic and welcome here, but you might be interested in our new Bioinformatics site. – terdon Jun 23 '17 at 9:25
13

With awk:

awk '$2~/^[A-Z][A-Z]/{ $2="PT_"$2 }1' xid.txt

The output:

xid: PT_SC48028 id: artf398444
xid: indv1000 id: indv24519
xid: PT_SC32173 id: artf398402
xid: PT_SC21033 id: artf398372
xid: 1001 id: tracker4868
xid: wiki1000 id: wiki10709
xid: proj1234 id: proj12556

  • $2~/^[A-Z][A-Z]/ - if the 2nd field starts with 2 uppercase letters

Or sed approach:

sed -i 's/^\(xid:[[:space:]]*\)\([A-Z]\{2\}[^[:space:]]*\)/\1PT_\2/' xid.txt
  • this was so smooth, instant answer thanks a lot. If i want to append in the existing input file what should be done ? – Subrat Sahoo Jun 23 '17 at 8:45
  • awk '$2~/^[A-Z]{2}/{ $2="PT_"$2 }1' xid.txt > xid-tmp && mv xid-tmp xid.txt or use my second approach – RomanPerekhrest Jun 23 '17 at 8:50
  • 1
    @SubratSahoo If this answer solved your issue, please take a moment and accept it by clicking on the check mark to the left. That will mark the question as answered and is the way thanks are expressed on the Stack Exchange sites. – terdon Jun 23 '17 at 9:25
  • 1
    Also, @SubratSahoo (and Roman) newer versions of GNU awk (the one you usually have installed on Linux systems) has -i inplace which allows you to edit a file in place, like sed and perl's -i. – terdon Jun 23 '17 at 9:27
  • @terdon, yes, I know about -i inplace (I've suggested a unified approach with mv command for the OP to fit portability). As for Bioinformatics beta community: I've just joined it. Could be there tasks related to Linux/Python programming/processing? How do you think? – RomanPerekhrest Jun 23 '17 at 9:48
6

sed option

sed -i -e 's/[A-Z][A-Z]/PT_&/' file

where

  • -i edit in place
  • -e command to execute

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.