1

I want to replace "-from" with "this" in the begining of line. This should happen when that line has 'R' at the end and line above it has "D" at the end.

For example for the block shown below:

-from XXXXXXXXXXXXXXXXX/D   
-from XXXXXXXXXXXXXXXXX/R   
-from XXXXXXXXXXXXXXXXX/K   
-from XXXXXXXXXXXXXXXXX/L   
-from XXXXXXXXXXXXXXXXX/G   
-from XXXXXXXXXXXXXXXXX/R 

the output should look like:

-from XXXXXXXXXXXXXXXXX/D   
-this XXXXXXXXXXXXXXXXX/R   
-from XXXXXXXXXXXXXXXXX/K   
-from XXXXXXXXXXXXXXXXX/L   
-from XXXXXXXXXXXXXXXXX/G   
-from XXXXXXXXXXXXXXXXX/R  

Anything is fine, sed, awk, grep, etc.

2 Answers 2

6
  • When the previous line has D at the end,
    • and when the current line has R at the end,
      • then the first word (-from) must be replaced by -this.

awk script:

# if the prev. line ended with D, and the current with R, replace first word
# optionally add && $1 == "-from"
has_d && /R$/ { $1 = "-this"; }
# print the current line, pretend that d is not matched yet
{ print; has_d = 0; }
# if line ends with D, set flag
/D$/ { has_d = 1; }

One liner:

awk 'has_d&&/R$/{$1="-this"}{print;has_d=0}/D$/{has_d=1}' yourfile
2
  • Goodness gracious, worked like a charm:)
    – Rana Khan
    Commented Nov 13, 2013 at 23:24
  • 3
    @RanaKhan - make sure to mark this as the accepted answer so others know your Q has been answered.
    – slm
    Commented Nov 14, 2013 at 0:18
1

In sed:

sed '/D$/{N;/R$/s/\n-from/\n-this/}' your_file

Expanded with comments:

sed ' /D$/{                          # If the current line ends in D
            N;                       # Append the next line to the pattern space
            /R$/s/\n-from/\n-this/   # If you find R at end-of-line, substitute
      }' your_file

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .