Shell-Script
替換括號之間的任何內容,即使跨越多行
我想使用 bash 或 shell 腳本並用空格替換兩個括號之間的**任何內容。**兩個括號之間的文本可以是多行,例如:
myFunction (line0 line1 line2 line3 line4)
我想轉換為:
myFunction ( )
AWK
AWK 允許在條件範圍內執行程式碼塊
{}
。在這種情況下,我們希望gsub()
在從包含的行(
到包含的行的每一行上執行)
。$ awk '$0~/[(]/,$0~/[)]/{gsub(/line/,"newline")};1' input.txt another line something else myFunction (newline0 newline1 whatever newline2 newline3 newline4) some other line
Python(原始答案)
這是一個可以完成這項工作的快速 python 腳本:
#!/usr/bin/env python3 from __future__ import print_function import sys with open(sys.argv[1]) as fp: flag = None for line in fp: clean_line = line.strip() if "(" in clean_line: flag = True if flag: clean_line = clean_line.replace("line","newline") print(clean_line) if ")" in clean_line: flag = False
測試執行:
$ cat input.txt another line something else myFunction (line0 line1 lilne2 line3 line4) some other line $ ./edit_function_args.py input.txt another line something else myFunction (newline0 newline1 newline2 newline3 line4) some other line
BASH 版本
相同的腳本,除了
bash
用sed
#!/bin/bash flag=false while IFS= read -r line do if grep -q '(' <<< "$line" then flag=true fi if $flag then line=$(sed 's/line/newline/' <<< "$line") fi printf "%s\n" "$line" if grep -q ')' <<< "$line" then flag=false fi done < "$1"
bash
接受@Serg的答案並將其轉換為使用 bash 內置函式,而不是每行 2 或 3 個程序。流程很便宜,但不是免費的!#!/bin/bash # Use shell builtins, read, true, false, printf flag=false while IFS= read -r line do case "$line" in (*"("*) flag=true ;; esac if $flag then line=${line//line/newline} fi printf "%s\n" "$line" case "$line" in (*")"*) flag=false ;; esac done < "$1"