簡體   English   中英

替換文件中特定行號的字符

[英]Replace character in file at specific line number

我有 index.html 文件

我想要第 88 行,如下所示: <h1>Test Page 1</h1>

變成這樣: <h1>Test Page 10</h1>

嘗試了基本程序,例如:

sed -i '88s/1/10' index.html

sed -i ‘88|\(.*\)|                 <h1>Test Page 10</h1>\1|' index.html

但似乎 html 標簽需要不同的處理?

I filled t.html with 100 lines of the same content (each line is just <h1>Test Page 1</h1> . For this demonstration I used nl t.html | grep 88; to show the 88th line. ( nl just每行編號, grep搜索要匹配的正則表達式,但88只匹配文字 88)。我在命令的開頭和結尾運行它,以顯示更改前后的第 88 行。

$ nl t.html | grep 88; sed -i -e '88 s/Page 1/Page 10/' t.html; nl t.html | grep 88
    88  <h1>Test Page 1</h1>
    88  <h1>Test Page 10</h1>

您必須小心使用正則表達式 - 如果您只使用s/1/10/ ,它將替換第一個h1中的1而不是Page 1 1

cat >> replace.ed << EOF
88s/e 1/e 10/
wq
EOF

ed -s index.html < replace.ed
rm -v ./replace.ed

利用

sed -E 's,(>[^<]*)1([^<]*<),\110\2,'

s,(>[^<]*)1([^<]*<),\110\2,將找到>和除<之外的任何文本,然后是1 ,然后是除<直到並包括<的任何文本,並將匹配替換為1之前的文本,然后是10 ,然后是1之后的文本。

漂亮的小班輪:

cat data.txt | awk 'NR==2'| sed 's/Test Page 1/Test Page 10/'

所以 AWK 命令使用 NR,這是目前看到的輸入行總數。 將其更改為相關的特定行號。 sed 命令實際上只是交換第一個和最后一個斜杠之間的所有內容。

希望這會有所幫助:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM