2
aaaaaaaaa   
bbbbbbbbb   
-th ccccccccc_RD \  

DDDDDDDD  
FFFFFFFF  
-th GGGGGGG_RD \

using sed/grep/awk etc, In the above text, if a line ends with "RD \" , replace "-th" with "-to" at the beginning of line. Desired output:

aaaaaaaaa   
bbbbbbbbb   
-to ccccccccc_RD \  

DDDDDDDD  
FFFFFFFF  
-to GGGGGGG_RD \

any help is greatly appreciated.

  • 2
    sed '/RD \\$/s/^-th/-to/' – jthill Nov 6 '13 at 17:58
6

This should work:

sed 's/^-th\(.*RD \\\)/-to\1/' foo.txt

This is slightly complex because \ is a special character and needs to be escaped. Since escaping is done by \ itself, the way of matching a literal \ is \\. The \( and \) are there to capture the matched pattern which is then referred to as \1 in the substitution.

The syntax is easier in Perl since the parentheses do not need to be escaped:

perl -pne 's/^-th(.*RD \\)/-to$1/' foo.txt

In awk you would do:

awk '/RD \\$/{$1="-to"}{print}' foo.txt 
  • didn't work:( it doent do anything, doesnt change anything – Rana Khan Nov 6 '13 at 18:02
  • @RanaKhan do you have trailing spaces after the \ at the end of the lines? Also, these solutions will not change the original file, you will need to redirect the output (sed 's/^-th\(.*RD\\\)/-to\1/' foo.txt > bar.txt) or use the -i flag with perl or sed: sed -i 's/^-th\(.*RD\\\)/-to\1/' foo.txt – terdon Nov 6 '13 at 18:04
  • @terdon Actually, I think it's because there's a space between RD and '\' (so your awk solution should work). – Joseph R. Nov 6 '13 at 18:07
  • @JosephR. thanks, I had actually corrected that in the version I tested and forgot to update my answer :). – terdon Nov 6 '13 at 18:08
  • 1
    @RanaKhan please post another question with followup issues. It is hard to understand what you mean from the comments. – terdon Nov 6 '13 at 18:35

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.