sjsam
sjsam

Reputation: 21955

sed option to append matched pattern to file

sed manual says :

The file will be created (or truncated) before the first input line is read; all w commands (including instances of the w flag on successful s commands) which refer to the same filename are output without closing and reopening the file.

So when I do :

sed '/pattern/w filename' file

The existing content in the file is deleted which is not good when I am dealing with log files.

How to make sed w option append content to a file instead of truncating it?

If a straight forward method is not available, any small tweaks are appreciated.

Upvotes: 1

Views: 432

Answers (2)

potong
potong

Reputation: 58371

This might work for you (GNU sed):

sed -n '/pattern/w/dev/stdout' file1 >>file2

This will append each line in file1 containing pattern to file2.

An alternative:

sed -n '/pattern/s/.*/echo "&" >>file2/e' file1

Upvotes: 2

shellter
shellter

Reputation: 37258

I thought there was an w >>file option for sed, but I can't find it anywhere.

You can get what you need with a similar construct in awk. i.e.

     awk -v outFile=/p/2/f/outfile '/pattern/{print $0 >> outFile }' inFile

IHTH

Upvotes: 1

Related Questions