AWKスクリプトのパターンに基づいてテキストの特定の部分を処理します。

AWKスクリプトのパターンに基づいてテキストの特定の部分を処理します。

私の好みに応じてtex文書をhtmlに変換するためにawkでスクリプトを開発しています。

#!/bin/awk -f

BEGIN {
    FS="\n";
    print "<html><body>"
}
# Function to print a row with one argument to handle either a 'th' tag or 'td' tag
function printRow(tag) {
    for(i=1; i<=NF; i++) print "<"tag">"$i"</"tag">";
}

NR>1 {
   [conditions]
   printRow("p")
}

END {
    print "</body></html>"
}

ご覧のとおり、それは非常に若い開発段階にあります。

\documentclass[a4paper, 11pt, titlepage]{article}
\usepackage{fancyhdr}
\usepackage{graphicx}
\usepackage{imakeidx}
[...]

\begin{document}

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla placerat lectus sit amet augue facilisis, eget viverra sem pellentesque. Nulla vehicula metus risus, vel condimentum nunc dignissim eget. Vivamus quis sagittis tellus, eget ullamcorper libero. Nulla vitae fringilla nunc. Vivamus id suscipit mi. Phasellus porta lacinia dolor, at congue eros rhoncus vitae. Donec vel condimentum sapien. Curabitur est massa, finibus vel iaculis id, dignissim nec nisl. Sed non justo orci. Morbi quis orci efficitur sem porttitor pulvinar. Duis consectetur rhoncus posuere. Duis cursus neque semper lectus fermentum rhoncus.

\end{document}

私が望むのは、スクリプトがライブラリ、変数などをインポートする前とその間の行だけを\begin{document}解釈することです\end{document}。今はそれに興味がありません。

そのパターン内のテキストのみを処理するにはどうすればよいですか?

ベストアンサー1

awkを呼び出すためにshebangを使用しないでください。状況がより複雑になり、シェル機能とawk機能を活用する能力が消え、スクリプトがawk固有の構文と緊密にリンクされます。https://stackoverflow.com/a/61002754/1745001

スクリプトを開始する方法は次のとおりです。

#!/usr/bin/env bash

awk '

    BEGIN {
        print "<html><body>"
    }
    
    # Function to print a row with one argument to handle either a "p" or "th" tag or "td" tag
    function printRow(tag,    i) {
        for(i=1; i<=NF; i++) print "<"tag">" $i "</"tag">"
    }
    
    $0 == "\begin{document}" { f=1 }
    $0 == "\end{document}"   { f=0 }
    
    !f { next }
    
    [conditions] {
       printRow("p")      # or "th" or "td"
    }
    
    END {
        print "</body></html>"
    }

' "${@:--}"

関数は1からNFまでのループを使用していたので削除しましたFS="\n"。これは、FSとRSが同じ場合は意味がありません。これはNFが常に1になるからです。

おすすめ記事