简体   繁体   中英

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 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_" grep "^ LOB" create_tables_clean.sql | grep "\\"L_"

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

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

Replace $myVar with your variable, obviously.

在此处输入图片说明

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)

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"('

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM