如何使用Chef::Util::FileEdit函数保留缩进?
Matching Indentation with
insert_line_after_match Absolutely feasible! You can easily make the inserted line inherit the exact indentation of the regex-matched line by leveraging regex capture groups to grab the leading whitespace from the matched line, then prepending that whitespace to your new content.
Here's a step-by-step breakdown:
- Modify your regex to capture indentation: Update your pattern to include a capture group for any leading whitespace (spaces or tabs) at the start of the matched line. Use
^(\s*)at the beginning of your regex—this will capture all whitespace before the actual content you're targeting. - Prepend the captured indentation to your new line: If your
insert_line_after_matchfunction supports a callback (common in many scripting contexts like Ruby's FileEdit), you can access the captured indentation and combine it with your new content.
Example Implementation
Let's adjust your original call to handle indentation properly:
file_xml.insert_line_after_match(/^(\s*)<cookie-path>\/analytics<\/cookie-path>/) do |match_result| # Extract the captured indentation from the regex match line_indent = match_result[1] # Prepend the indentation to your new line content "#{line_indent}<cookie-secure>true</cookie-secure>" end
How this works:
- The regex
^(\s*)<cookie-path>\/analytics<\/cookie-path>captures all leading whitespace (spaces/tabs) from the line containing your target<cookie-path>element into the first capture group. - The callback uses that captured whitespace (
line_indent) to format the new<cookie-secure>line, ensuring it matches the exact indentation of the line you're inserting after.
If your insert_line_after_match doesn't support callbacks, you can first locate the matched line, extract its indentation manually, then pass the pre-indented string directly to the function. For example:
# First, find the matched line to get its indentation matched_line = file_xml.grep(/<cookie-path>\/analytics<\/cookie-path>/).first line_indent = matched_line.match(/^(\s*)/)[1] # Now insert the pre-indented line file_xml.insert_line_after_match(/<cookie-path>\/analytics<\/cookie-path>/, "#{line_indent}<cookie-secure>true</cookie-secure>")
This approach ensures your new line blends seamlessly with the existing XML structure, maintaining consistent formatting.
内容的提问来源于stack exchange,提问作者Raamish Malik
相关产品推荐
相关产品推荐

