FreshTransistor
FreshTransistor

Reputation: 109

regex to select before semi colon

Input string

key=value ; export key

want to select just value

regex [^=]*; giving including ;. How can I remove that ?

sed '/key/ s/[^=]*;/myValue/' fileName

will above command work to replace value with myValue in line having key ?

Upvotes: 0

Views: 332

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627199

You can use

sed 's/\(key=\)[^; ]*/\1myValue/' file > newfile

The \(key=\)[^; ]* pattern matches and captures in Group 1 the key= substring and then matches any zero or more chars other than spaces and semi-colons. The \1 in the replacement pattern refers to the Group 1 value, so key= is kept in the result.

See this online demo:

#!/bin/bash
s='key=value ; export key'
sed 's/\(key=\)[^; ]*/\1myValue/' <<< "$s"
# => key=myValue ; export key

Upvotes: 1

William Pursell
William Pursell

Reputation: 212504

Seems like you are looking for:

 sed -E '/^key=/s/=[^;]*/=myvalue/'

Upvotes: 0

Related Questions