sed: replace a match with the same match and add more text

I have a file called config.properties that contains the following text:

cat config.properties

// a lot of data
com.enterprise.project.AERO_CARRIERS = LA|LP|XL|4M|LU|4C
//more data

and my goal is keep the same data but adding more. For this example i want to add to the assignment of this variable |JJ|PZ results in:

cat config.properties

// a lot of data
com.enterprise.project.AERO_CARRIERS = LA|LP|XL|4M|LU|4C|JJ|PZ
//more data

The command that I've been using for this is :

 sed 's/\(com\.enterprise\.project\.AERO_CARRIERS\s*\=\s*.+\)/\1\|JJ\|PZ/g' config.properties

But this doesn't works. What am I doing wrong?

Upvotes: 0

Views: 61

Answers (3)

Walter A
Walter A

Reputation: 20022

You can match first:

sed '/com\.enterprise\.project\.AERO_CARRIERS\s*\=\s*.\+/ s/$/|JJ|PZ/g' config.properties

Upvotes: 0

Inian
Inian

Reputation: 85800

As an alternative to use stream-editors like sed, just use the native text editor, ed from UNIX-days for in-place search and replacement. The option used (-s) is POSIX compliant, so no issues on portability,

printf '%s\n' ",g/com.enterprise.project.AERO_CARRIERS/ s/$/\|JJ\|PZ/g" w q | ed -s -- inputFile

The part ,g/com.enterprise.project.AERO_CARRIERS/ searches for the line containing the pattern, and the part s/$/\|JJ\|PZ/g appends |JJ|PZ to end of that line and w q writes and saves the file, in-place.

Upvotes: 1

SLePort
SLePort

Reputation: 15461

\s and + are not POSIX compliant:

  • you can match spaces and tabs with [[:blank:]] and whitespace characters(including line breaks) with [[:space:]].

  • .+ can be replaced with .\{1,\} or ..*

And you don't need to use backreference here, use & instead to output lines matching your pattern:

sed 's/^com\.enterprise\.project\.AERO_CARRIERS[[:blank:]]*=[[:blank:]]*.\{1,\}/&|JJ|PZ/'

Upvotes: 1

Related Questions