Nir
Nir

Reputation: 2629

How to use sed to replace partial of a find

some of the lines in a file look like this:

 LOB ("VALUE") STORE AS SECUREFILE "L_MS_WRKNPY_VALUE_0000000011"(
 LOB ("INDEX_XML") STORE AS SECUREFILE "L_HRRPTRY_INDX_L_0000000011"(

What I can assume is that in the "*" the string starts with an L_ and ends in 10 chars number.

I want for each line that:

  1. start with LOB (white-space before the LOB)
  2. inside "" the first two letters are L_
  3. line always ends with "(

replace the last 10 chars in the "" with variable.

all I manage to do is: cat /tmp/out.log | sed 's/_[0-9_]*/$NUM/g' > /tmp/newout.log

to find the required rows I run: grep "^ LOB" create_tables_clean.sql | grep "\"L_"

However I dont know how to combine the two and get what I wish.

Upvotes: 0

Views: 984

Answers (2)

BMW
BMW

Reputation: 45263

several useless characters are in accepted sed command, here is shorter one.

sed -r 's/(LOB.*"L_.*)([0-9]{10})("\()/\1'$myVar'\3/' file

Second, @Basti M, when you need echo with double quotes in string, use singe quotes, then you needn't escape the double quotes.

echo 'LOB ("VALUE") STORE AS SECUREFILE "L_MS_WRKNPY_VALUE_0000000011"('

Upvotes: 0

KeyNone
KeyNone

Reputation: 9150

sed -r 's/(\sLOB.*"L_.+_)([0-9]{10})("\()/\1'$myVar'\3/'

Replace $myVar with your variable, obviously.

enter image description here

I made three capturing groups:

(\sLOB.*"L_.+_)  #catches everything until the 10 numbers
([0-9]{10})      #catches the 10 numbers
("\()            #catches the last "(

The first capturing group matches only if your line starts with LOB (with a preceeding whitespace) and contains "L_.
Then you simply substitute the second capturing group (containing only the 10 numbers) with your variable while keeping the first and third capturing group (\1'$myVar'\3).

Your whole call would look like

cat /tmp/out.log | sed -r 's/(\sLOB.*"L_.+_)([0-9]{10})("\()/\1'$NUM'\3/g' > /tmp/newout.log

(notice I added the g-modifier to the regex, so it will match every occurence)

Upvotes: 1

Related Questions