Tony Stark
Tony Stark

Reputation: 3463

using sed with regular expression

I want it to detect the following pattern in FILE_1:

STRING_1   :   "STRING_2"

and append STRING_2 to FILE_2

This is what I have right now:

sed 's/STRING_1\s*:\s*"\([^"]*\)"/\1/g' FILE_1 >> FILE_2;

but this doesn't work, it appends a lot of random stuff to FILE_2(that are not supposed to match). Not sure what I did wrong ...

Upvotes: 2

Views: 279

Answers (4)

Jens
Jens

Reputation: 72746

Use sed -n if you don't want sed to output each line by default and the p modifier to print the result of a match.

sed -n -e 's/foo/bar/gp' FILE_1 >> FILE_2

Upvotes: 0

DaveC
DaveC

Reputation: 2050

A bit of a risk to answer by changing the question spec but...

perl -ne 'print "$1\n" if ( /.*STRING_1\s*:\s*\"([^"]*)\".*/)' FILE_1 >> FILE_2

appears to work fine

Upvotes: 1

Tony Stark
Tony Stark

Reputation: 3463

changed it to:

sed 's/.*STRING_1\s*:\s*"\([^"]*\)".*/\1/g' FILE_1 >> FILE_2;         

but it still appends the whole file instead of the regex match

Upvotes: 0

codaddict
codaddict

Reputation: 455410

If there is text before STRING_1 and after STRING_2 , it'll not be removed with your current regex and hence will get appended to FILE_2.

To fix this add .* at the beginning and at the end of your current pattern as:

sed 's/.*STRING_1\s*:\s*"\([^"]*\)".*/\1/g' FILE_1 >> FILE_2;
       ^^                          ^^

Upvotes: 1

Related Questions