开发者

sed - command to match a line, and change only a numerical part?

开发者 https://www.devze.com 2023-01-28 23:33 出处:网络
I have this as my target file: #define NUMTHREADS 4 #define ar 1000 #define ac 1000 #define br 1000 #define bc 1000

I have this as my target file:

#define NUMTHREADS 4
#define ar 1000
#define ac 1000
#define br 1000
#define bc 1000

I want to replace just the numbe开发者_开发百科rs in these lines with different numbers using sed (doing this is a bash script). However, I don't want to change these values anywhere else in the file. The script can't know the values directly because they may be different than listed above.

So basically:

Find line with #define ar then replace a general numerical match after it with a given number. Is this possible with sed?


Sure, that's pretty much the point of regular expressions:

sed [-i] 's/^#define ar [0-9]\+$/#define ar 12345/' <file>

The -i switch causes sed to operate on the file in-place; leave it off the first time to let it print to stdout and make sure it does what you want.

Of course, from your first description it sounds like you might want to match more than just #define ar. To match all two-letter #defines:

sed [-i] 's/^\(#define [a-z]\{2\}\) [0-9]\+$/\1 12345/`

The \1 is replaced by whatever was matched by the \(...\) group.

0

精彩评论

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