You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用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_match function 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:30:17