簡體   English   中英

Bash / Shell將x到y行中的一小段文本替換為另一個文件的內容中包含的兩行

[英]Bash/Shell replace a chunk of text from line x to line y both lines included with contents of another file

可以說我在文件A中有此內容

1 <div class="a"></div>
2 <div class="b"></div>
3 <div class="c"></div>
4 <div....
5 ...
6 ...
7 ...
8 ...
9 <div class="i"></div>

我包含的行號實際上並不存在

我的腳本中有兩個變量,分別是start_lineend_line這些變量包含我要開始替換的行和我要結束替換的行

然后,我有一個文件B,它也是一個稱為export的變量,其中包含一些文本,這些文本也是HTML標記(編輯:認為這是不相關的-但事實並非如此)

當我知道這些數字為變量並想用也是變量的文件內容替換(可以是文件位置或cat變量)時,如何將文件A中的所有行從第4行替換為第7行我猜也是)

被sed和范圍對象弄亂了-n但是是的...還有一些awk-但是這里的shell和bash總共n00b

到目前為止,我已經嘗試過了(變量名稱不盡相同,但是我希望它有道理

sed "-n${start_line},${end_line} s/${stump_text}" "$export_file"

編輯:我不好,我沒有告知實際要替換的文本是HTML

嘗試

sed -e "${start_line} r ${fileB}" -e "${start_line},${end_line} d" "$fileA"

由兩個表達式組成:

  • -e "${start_line} r ${fileB}"讀取${fileB}指定的文件內容,並將其添加到${start_line}指定的行地址之后
  • -e "${start_line},${end_line} d刪除這些地址范圍內的行

在awk中:

$ cat foo.awk
NR==start {                     # at start, output fileB.txt
    while (getline < file) 
        print }
NR>=start && NR <= end { next } # between start and end do nothing
1                               # print

運行:

$ fileb=fileb.txt;  start=4;  end=7    # your values into variables
$ awk -v file=$fileb  -v start=$start  -v end=$end  -f foo.awk  fileA.txt

如果我沒有理解你的意思,和$export_file包含文件的名稱和$stump_text文本,以取代從內容$start_line$end_line用,這應該去:

sed -i '${start_line},${end_line}s/.*/${stump_text}/' "$export_file"

使它正常工作,但效果不佳-可能會變得更漂亮。

由於發生轉義問題,我無法將其導入為字符串。 我無法保留從fileB到fileA的插入,因此需要一個tmp文件來保存

這是解決方案

sed -i "${start_line},${end_line}d" "$fileA"
sed -e "${start_line}r ${fileB}" "$fileA" > "$fileA.out"
mv "$fileA.out" "$fileA"

如果有人可以使其更漂亮,請這樣做-我需要學習:-)

暫無
暫無

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

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