3

I want to delete all the text after the second underscore (including the underscore itself), but not on every line. Every of the target lines begin with a pattern (>gi_).

EXAMPLE.

Input

>gi_12_pork_cat

ACGT

>gi_34_pink_blue

CGTA

Output

>gi_12

ACGT

>gi_34

CGTA

3

for the lazy among us:

cut -d_ -f1,2 input

gives us:

bash-[514]$ cat input
>gi_12_pork_cat   
ACGT
>gi_34_pink_blue    
CGTA

bash-[515]$ cut -d_ -f1,2 input
>gi_12
ACGT    
>gi_34
CGTA
2

There is also a short hand using awk:

awk -F_ '{print $1 (NF>1? FS $2 : "")}' yourfile
1
$ awk -F_ 'BEGIN {OFS="_"} /^>gi/ {print $1,$2} ! /^>gi/ {print}' input
>gi_12
ACGT
>gi_34
CGTA
1
  • Golfing: awk -F_ 'BEGIN {OFS="_"} /^>gi/ {print $1,$2;next}1' input Jun 12 '17 at 19:47
1
sed -ne '/^>gi_/s/_/\n/2;P' yourfile

Explanation

  • Only for lines that begin with the string >gi_ are we to try to effect the sub _ ---> \n. Then we print the pattern space using the P command which prints upto the first newline if it finds one or the whole of it.

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.