SamJ
SamJ

Reputation: 23

Replace string and insert a character at a certain position in the same field

Hi I'm trying to replace \_\_SEC\_\_00 with $6$ and insert a $ after the 19 character in that certain field.

Data:

Avivit Katzir,avivit,\_\_SEC\_\_00wLaxAKg1ecw80jGW0ACTr.kI5gttGo/YxHHUOeCZzDn8.3yFyPqJSKwXXYfBVPjco7RKPjK/1XBvYQAXC4jKm9pt8G6WtMrIRs0Lp/,demo,demo,demo

Expected output:

Avivit Katzir,avivit,$6$wLaxAKg1ecw80jGW$0ACTr.kI5gttGo/YxHHUOeCZzDn8.3yFyPqJSKwXXYfBVPjco7RKPjK/1XBvYQAXC4jKm9pt8G6WtMrIRs0Lp/,demo,demo,demo

I tried this command:

sed -e 's/\\_\\_SEC\\_\\_../\$6\$/' -e 's/./&\$/19'

But I have a problem in inserting $.

Upvotes: 1

Views: 808

Answers (2)

RavinderSingh13
RavinderSingh13

Reputation: 133478

In awk, with shown samples could you please try following, based on your shown samples written in GNU awk. You could change from \\_\\_SEC\\_\\_00 to \\_\\_SEC\\_\\_.. in case you want to match any characters here.

awk '
match($0,/\\_\\_SEC\\_\\_00/){
  print substr($0,1,RSTART-1) "$6$"\
  substr($0,RSTART+RLENGTH,16)"$"\
  substr($0,RSTART+RLENGTH+16)
}' Input_file

Explanation: Adding detailed explanation for above.

awk '                                  ##Starting awk program from here.
match($0,/\\_\\_SEC\\_\\_00/){         ##using match function of awk here to match regexp \\_\\_SEC\\_\\_00, notice double \\ to escape \ here.
  print substr($0,1,RSTART-1) "$6$"\   ##Printing sub string from 1st index of line to just before 1 index of matched pattern then printing $6$
  substr($0,RSTART+RLENGTH,16)"$"\     ##Printing sub string after matched part till next 16 characters here thne printing $ here.
  substr($0,RSTART+RLENGTH+16)         ##Printing rest of the line from here.
}' Input_file                          ##mentioning Input_file here.

Upvotes: 2

oguz ismail
oguz ismail

Reputation: 50750

All you need is a capturing group there.

sed -E 's/\\_\\_SEC\\_\\_..(.{16})/$6$\1$/'

Upvotes: 1

Related Questions