Text-Processing
如何使用 awk 根據簡單的規則縮進源文件?
如何根據幾個簡單的規則縮進原始碼?
例如,我使用了 sed 並要求將 selenium HTML 源表轉換為以下類似 rspec 的程式碼。我怎麼能始終如一地縮進和之間
describe
的行end
?理想情況下,我希望能夠添加縮進describe "Landing" do visit("http://some_url/url_reset") visit("http://some_url/url_3_step_minimal_foundation") # comments expect(css_vehicle1_auto_year) to be_visible end describe "Stage1" do wait_for_element_present(css_vehicle1_auto_year option_auto_year) select(auto_year, from: css_vehicle1_auto_year) ... end describe "Stage2" do fill_in(css_driver1_first_name, with: driver1_first_name) fill_in(css_driver1_last_name, with: driver1_last_name) ... submit(css_policy_form) expect(css_vehicle1_coverage_type) to be_visible end describe "Stage3" do wait_for_element_present(css_vehicle1_coverage_type) select(coverage_type, from: css_vehicle1_coverage_type) find(css_has_auto_insurance).click ... submit(css_policy_form) expect(css_quotes) to be_visible end
所以我有
describe "Landing" do visit("http://some_url/url_reset") visit("http://some_url/url_3_step_minimal_foundation") # comments expect(css_vehicle1_auto_year) to be_visible end describe "Stage1" do wait_for_element_present(css_vehicle1_auto_year option_auto_year) select(auto_year, from: css_vehicle1_auto_year) ... end describe "Stage2" do fill_in(css_driver1_first_name, with: driver1_first_name) fill_in(css_driver1_last_name, with: driver1_last_name) ... submit(css_policy_form) expect(css_vehicle1_coverage_type) to be_visible end describe "Stage3" do wait_for_element_present(css_vehicle1_coverage_type) select(coverage_type, from: css_vehicle1_coverage_type) find(css_has_auto_insurance).click ... submit(css_policy_form) expect(css_quotes) to be_visible end
現有 sed 和 awk 的原始碼位於https://jsfiddle.net/4gbj5mh4/,但它真的很亂,不是我要問的。我掌握了簡單的 sed 和 awk 的竅門,但不知道從哪裡開始。
如果它也可以處理遞歸,那就太好了。對我來說不是必需的,但概括可能對使用這個問題的其他人有用,即
describe "a" do describe "b" do stuff more stuff end end
到
describe "a" do describe "b" do stuff more stuff end end
順便說一句,我也在進行這種自定義轉換,部分原因是我在 selenium 中將變數用作頁面對象,並且它們破壞了對 rspec 的內置導出。
與
awk
:awk ' /^end/ { sub(" ", "", indent) } # Or { indent = substr(indent, 3) } { print indent $0 } /^describe/ { indent = indent" " } ' <file