开发者

sed regex - matching text between two double quotes when a pattern appears in the line

开发者 https://www.devze.com 2023-02-14 21:29 出处:网络
Using batch PHP from linux shell I am trying to replace the license number in a config file below with a different one. The config line in question may not always appear the same but may or may not ha

Using batch PHP from linux shell I am trying to replace the license number in a config file below with a different one. The config line in question may not always appear the same but may or may not have spaces, tabs, etc.

Examples:

$co开发者_开发百科nfig['license_number'] = "jfur2e2ev9uhuvcfu";
$config['license_number'] ="jfur2e2ev9uhuvcfu";
$config['license_number']    ="";
$config['license_number']= "jfur2e2ev9uhuvcfu";
$config[ 'license_number' ] = "jfur2e2ev9uhuvcfu";

The key is to find any line with "license_number" (or any other text specified) and replace whatever is between the double quotes with the new config parameter.

I would like to use sed so that I can look in all files recursively. I have tried positive lookbehind but I cannot define a fixed length text to search.


This assumes that there is only one occurrence per line:

sed '/license_number/s/"\([^"]*\)"/"foo"/' inputfile

In Perl, you can use \K for variable length positive lookbehinds.


Sometimes the solution can be solved without much regex. Try awk

$ awk 'BEGIN{OFS=FS="="}/license_number/{$2="\"foo\""}1'  file
$config['license_number'] ="foo"
$config['license_number'] ="foo"
$config['license_number']    ="foo"
$config['license_number']="foo"
$config[ 'license_number' ] ="foo"

this says when "license_number" is found, change to 2nd field to "foo". The input field seperator and output field separator are set to "=".

0

精彩评论

暂无评论...
验证码 换一张
取 消