3

I have a file like this (with much more lines):

01200 Carbon metabolism (1)

01210 2-Oxocarboxylic acid metabolism (1)

01212 Fatty acid metabolism (2)

01230 Biosynthesis of amino acids (1)

00020 Citrate cycle (TCA cycle) (1)

and I want to replace the first and the last space for a tab, like this:

01230\tBiosynthesis of amino acids\t(1)

00020\tCitrate cycle (TCA cycle)\t(1)

I tried the following:

sed 's/ /\t/;s/ (/\t(/' eg_kaas_pwmap > res.tsv

It worked, but in lines as in the line with "(TCA cycle)", I got the \t before it, like:

00020\tCitrate cycle\t(TCA cycle) (1).

I tried some modifications, but none of it worked.

What should I do?

3

This will replace the first and last spaces with tabs:

sed -E 's/^([^ ]*) /\1\t/; s/ ([^ ]*)$/\t\1/' pwmap

For example:

$ sed -E 's/^([^ ]*) /\1\t/; s/ ([^ ]*)$/\t\1/' pwmap
01200   Carbon metabolism       (1)
01210   2-Oxocarboxylic acid metabolism (1)
01212   Fatty acid metabolism   (2)
01230   Biosynthesis of amino acids     (1)
00020   Citrate cycle (TCA cycle)       (1)

How it works

  • s/^([^ ]*) /\1\t/

    The regex ^([^ ]*) matches all nonblanks from the beginning of the line up to the first blank and puts them in group 1. This is replaced with group 1 followed by a tab.

  • s/ ([^ ]*)$/\t\1/

    The regex ([^ ]*)$ matches from the last blank to up to the end of the line with all the non-blanks stored in group 1. This is replace with a tab followed by group 1.

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.