简体   繁体   中英

replace string with variable on file

I have files with several lines like:

 ) extent size 256 next size 512 lock mode row;
  ) extent size 512 next size 512 lock mode row;
  ) extent size 256 next size 512 lock mode row;
  ) extent size 512 next size 512 lock mode row;
  ) extent size 256 next size 512 lock mode row;
  ) extent size 512 next size 512 lock mode row;
  ) extent size 512000 next size 48 lock mode row;
  ) extent size 512 next size 512 lock mode row;

I would like to change all this lines to:

) extent size 16 next size 16 lock mode row;

I can get all with:

cat file | grep "extent size" 

But I don't know how to change variable text

Thanks for any help,

SP

You want to replace all digit chunks with some other number on lines that contain extent size .

You may use the following sed solution:

val=16;
sed "/extent size/{s/[0-9]\{1,\}/$val/g}" file > newfile

Details

  • /extent size/ - finds lines that contain this text
  • {s/[0-9]\\{1,\\}/$val/g} - on the found line, replaces one or more digits with the val contents (assuming it will be a simple number, no additional processing is required).

See the online sed demo .

If comfortable with awk solution. Try this:-

grep "extent size" filename | awk '$4=$7="16"' 

Explanation

grep "extent size" => Grep the line contain words **"extent size"** 
awk '$4=$7="16"'   => change the value of **column 4 and 7** to 16.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM