-1

I would like to move the first string between > and the first _ to the second position after the first _

This is to transform this:

>10E13JB10_Vacares_8__a1
blablabla
>10E13JB10_Vacares_8__a2
blablabla
>10E2JB10_Mulhacen_13__a1
blablabla

Into this:

>Vacares_10E13JB10_8__a1
blablabla
>Vacares_10E13JB10_8__a2
blablabla
>Mulhacen_10E2JB10_13__a1
blablabla
ilkkachu
  • 133,243
  • 15
  • 236
  • 397

1 Answers1

4
sed -e 's/^>\([^_]*\)_\([^_]*\)/>\2_\1/' -i file

Find the first two strings terminated by _, and reverse their order in the substitution. Since it only matches the first two strings, it does not modify or discard the rest of the line.

  • s/aaa/bbb/ - perform a substitution, replacing all occurrences of aaa with bbb
  • ^ - begin of line
  • \(...\) - capture groups, which save the matched strings as \1 and \2
  • [^_]* - a character class matching all characters except _
jpaugh
  • 319
  • 2
  • 13
Ipor Sircer
  • 14,376
  • 1
  • 27
  • 34
  • 1
    You should explain what you're doing here at least a little bit. – Centimane Oct 11 '16 at 14:16
  • 2
    I agree with Centimane. Someone new to regexes will freak when they see this... I added a (prose) description, but it's under peer review. – jpaugh Oct 11 '16 at 14:48
  • Note that `-i` (for in place editing) is a GNU extension, not standard Sed. But this is still a good answer. Also see [How to achieve portability with sed -i (in-place editing)?](http://unix.stackexchange.com/q/92895/135943) – Wildcard Nov 05 '16 at 02:44