Search code examples
bashtextsededit

Insert line jump according to a condition, Bash Ubuntu


I have the following text to edit in ubuntu's bash:

Fo, 68

Fo, 55**Fm**,   328

Fv, 273

Fv/Fm,  0.832

PAR,
    
TEMP,

Fs, 65

Fm',    91

èPS2,   0.286,

The text continues but the above is the fundamental unity.

I want to insert a line jump before the first Fm (in the second line, not means that it is only in the second one), so I tried with:

sed -e 's/Fm/\nFm/g'

But this command insert a line jump after the bar / of Fv/Fm too. I want to avoid that because is my interest to conserve the Fv/Fm as it. In other words, I need to conserve Fv/Fm in that form.

Thank you!


Solution

  • Assumptions:

    • want to insert a \n before the string Fm if ...
    • the character preceding the Fm is a number ([0-9])
    • there may be more than one replacement to perform in the entire file (ie, don't limit replacement to just the first occurrence)

    Sample input (last 3 lines added to demonstrate assumptions):

    $ cat x
    Fo, 68
    Fo, 55Fm,   328                # insert '\n' before this 'Fm'
    Fv, 273
    Fv/Fm,  0.832                  # leave this 'Fm' alone
    PAR,
    TEMP,
    Fs, 65
    Fm',    91                     # leave this 'Fm' alone
    èPS2,   0.286,
    Fo, 33Fm,   328                # insert '\n' before this 'Fm'
    Fo, 9XFm,   328                # leave this 'Fm' alone
    Fo, 97Fm,   328                # insert '\n' before this 'Fm'
    

    One sed idea:

    $ sed  '/[0-9]Fm/ s/Fm/\nFm/' x
    Fo, 68
    Fo, 55
    Fm,   328                      # '\n' inserted before this 'Fm'
    Fv, 273
    Fv/Fm,  0.832                  # leave this 'Fm' alone
    PAR,
    TEMP,
    Fs, 65
    Fm',    91                     # leave this 'Fm' alone
    èPS2,   0.286,
    Fo, 33
    Fm,   328                      # '\n' inserted before this 'Fm'
    Fo, 9XFm,   328                # leave this 'Fm' alone
    Fo, 97
    Fm,   328                      # '\n' inserted before this 'Fm'