Unixを使用してすべてのHTMLファイルの名前をタイトルに変更するには?

Unixを使用してすべてのHTMLファイルの名前をタイトルに変更するには?

たとえば、ディレクトリ内のすべてのHTMLファイルの名前をTEXT?に含まれるテキストに変更します。

grep、sed、mvの組み合わせは機能できますか?

たとえば、1.htmlを含むファイルがあります。 1.htmlのタイトルはHTMLファイルにTEXTとして含まれています(タイトルタグTEXTに含まれています。1.htmlの名前をTEXT.htmlに変更したい)。

ファイル名が5.htmlで、5.htmlのタイトルがTEST2の場合は、5.htmlの名前をTEST2.htmlに変更したいと思います。

ベストアンサー1

for file in *.html ; do 
    name="$(sed -n '/<title>/{s=[^>]*title>==;s=</title.*==;s=[^0-9A-Za-z-_]=_=g;p;q}' "$file")"
    if [ -f "$name" ]; then
       [ -f "${name}_$file" ] || mv -f "$file" "${name}_$file"
    else
       mv -v "$file" "${name}.html"
    fi
done

sed説明する:

    /<title>/ -- finds the string with <title> and 
                 applies a group of commands to it
    {}        -- a group of commands
    s=[^>]*title>== -- removes everything before <title> including tag
    s=</title.*==   -- removes everything after </title> including tag
    s=[^0-9A-Za-z-_]=_=g -- substitute all non alphabet/num characters to _  
    p -- print the output
    q -- exit as there is no need to process rest of the file

echoPS:各タスクを実行する前に乾燥モードで実行し、mvすべてがうまく見えることを確認してください。

pps。 sed 構成は fdjskjfls が 1 行にあることも期待しており、同じ行に前にトークンはありません。

おすすめ記事