Search code examples
linuxbashunixsed

How to insert a character in front of a line one line above a specific character?


In my text file there are many lines whose contents are almost the same. Here are some of them.

So, what I want is to overwrite the / with - on every line and then insert - in front of the line exactly above the line that has the / character overwritten.

Right now I'm trying:

cat text | sed "/\//s/^/- /g;s/\/ /\n- /g"

Input file:

1
00:00:00,000 --> 00:00:00,000
You are older.

2
00:00:00,000 --> 00:00:00,000
By length of a sunset.
/ Is older.

3
00:00:00,000 --> 00:00:00,000
Soona.

4
00:00:00,000 --> 00:00:00,000
Noa!
/ Noa, wait!

Expected output:

1
00:00:00,000 --> 00:00:00,000
You are older.

2
00:00:00,000 --> 00:00:00,000
- By length of a sunset.
- Is older.

3
00:00:00,000 --> 00:00:00,000
Soona.

4
00:00:00,000 --> 00:00:00,000
- Noa!
- Noa, wait!

Solution

  • I find with this kind of request (do something on the previous line), it's easier to reverse the file, do something on the next line, then re-reverse the file.

    tac file | awk 'sub(/^\//, "-") {print; getline; $1 = "- " $1)} 1' | tac
    

    Here, I'm taking advantage of the fact that the sub() function returns the number of substitutions made, which can be treated as a boolean value.


    With sed

    tac file | sed '/^\// { s//-/; N; s/\n/&- /; }' | tac
    

    This is with the native sed on my Mac. I don't recall if GNU sed complains about the semicolon before the closing brace