简体   繁体   English

如何使用sed替换部分查找

[英]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. 我可以假设的是,在"*" ,字符串以L_开头,以10个字符的数字结尾。

I want for each line that: 我想要每一行:

  1. start with LOB (white-space before the LOB ) 开始与LOB (之前的空白LOB
  2. inside "" the first two letters are L_ "" ,前两个字母是L_
  3. line always ends with "( 行始终以"(

replace the last 10 chars in the "" with variable. 用变量替换""的最后10个字符。

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 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_" 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. 显然,用您的变量替换$myVar

在此处输入图片说明

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_ . 仅当您的行以LOB (前面有空格)开头且包含"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 ). 然后,您只需用变量替换第二个捕获组(仅包含10个数字),同时保留第一个和第三个捕获组( \\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) (注意,我将g修饰符添加到了正则表达式中,因此它将匹配每次出现的情况)

several useless characters are in accepted sed command, here is shorter one. 接受的sed命令中有几个无用的字符,此处较短。

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. 其次,@ Basti M,当您需要在字符串中用双引号引起回声时,请使用单引号,然后就不必转义双引号了。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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