[英]bash/sed, replace line in file at same indentation level
我正在尋找替換文件中的行。 即,如果“oldtext”在文件中的行首,則將整行替換為“newtext”。
行首可以是^oldtext
或oldtext
將縮進一些空格/制表符
grep "^[\S]oldtext" myfile.txt # doesn't work
我需要計算與“oldtext”相同的縮進級別
prefixspaces = <number of spaces before the "mytext", converting tabs to 4 spaces>
我意識到 sed 可能是實現此目的的最佳方法,但我不知何故需要先計算前綴空間,然后我的 output 類似於:
sed -i -e 's/^$prefixspaces$newtext*$/$prefixspaces$newtext/g' myfile.txt
無法弄清楚如何計算這個。 也許$prefixspace
可以放在組()
或其他東西中,以便 sed 可以輕松計算和使用它? 可能這是一個 sed 或 awk 單線,但我經過一番搜索無法解決。
像這樣:
sed 's/^\( *\)oldtext.*/\1newtext/' file
解釋:
搜索
^ beginning of the line
\( *\) capture 0 or more spaces in group 1
oldtext 'oldtext'
.* rest of the line
代替
\1 the 0 or more spaces from group1
newtext 'newtext'
sed
除了已接受的答案之外,另一種方法是使用 class 個字符([[:space:]])和帶有-r
參數的擴展正則表達式:
$ sed -r 's/^([[:space:]]*)oldtext.*/\1newtext/' << _eof
oldtext this
a
oldtext also this
_eof
結果將是:
newtext
a
newtext
在([[:space:]]*)
中,我們捕獲了一個具有零個或多個空格的組,但我們可以指定一個特定的數字。
awk
我們可以使用gsub
替換空格並計算次數:
$ awk \
-v old="oldtext" \
-v new="newtext" \
'BEGIN{re="^[[:space:]]*"old}
{
if (match($0,re)) {
i=gsub(/ /,"")
while (--i) printf " "
print new
}
else
print
}' << _eof
oldtext this
oldtext also this
oldtext and this
oldtext also this
_eof
結果將是:
newtext
newtext
newtext
newtext
perl
我們可以使用類似 sed的perl
來實現:
$ perl -lpe 's/^(\s*)oldtext.*/\1newtext/' << _eof
oldtext this
oldtext this
oldtext this
oldtext also this
_eof
結果將是:
newtext
newtext
newtext
newtext
這可能對你有用(GNU sed):
sed '/^\s*oldtext/s/\S.*/newtext/' file
匹配行首或縮進的oldtext
,並從第一個非空白字符開始替換。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.