指定された行が見つかった場合は、リストの行を別のファイルに追加する方法は?

指定された行が見つかった場合は、リストの行を別のファイルに追加する方法は?

デフォルトでは2つのファイルがあります。次のルータとスイッチのログインプロンプトのリストがあります。

user@router1
user@router2
user@switch1
user@switch2

別のファイルには、次のXMLチャンクがあります。

<headTag>
    <anotherTag1>
    <anotherTag2>
    </anotherTag2>
    </anotherTag1>
</headTag>
<headTag>
    <anotherTag1>
    <anotherTag2>
    </anotherTag2>
    </anotherTag1>
</headTag>

だから私がしたいのは、XMLファイルを繰り返し検索するたびに、<headTag>ルーター/スイッチリストの次の項目をその上の行に配置することです。その後、最終出力は次のようになります。

user@router1
<headTag>
    <anotherTag1>
    <anotherTag2>
    </anotherTag2>
    </anotherTag1>
</headTag>
user@router2
<headTag>
    <anotherTag1>
    <anotherTag2>
    </anotherTag2>
    </anotherTag1>
</headTag>

この目標をどのように達成できますか?私はRed Hat Enterprise Linux Serverを使用しており、ルーター/スイッチのリストに約800個のエントリがあり、同じ数のXMLチャンクがあります。

ベストアンサー1

別の短い解決策は次のとおりです。sedそしてed

XMLファイルを変更します。所定の位置に。コンソール出力を無視します。

sed -e 's#.*#/<headTag>/i\n&\n.\n//\nw#' PATH_TO_LIST_FILE | ed PATH_TO_XML_FILE

コマンドラインは、sedリストファイルの各行に対して次のEdコマンドを作成します。

/<headTag>/i                # search for tag and insert before
user@router1                # text to insert (= the current line in the list file)
.                           # end of insert
//                          # skip current tag (we are now on the line above the current tag))
w                           # save (could be postponed to the end, but makes the command shorter...)

<headTag>このコマンドでは、常にxmlファイルの行の先頭になければなりません。

おすすめ記事