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

추신. 건조 모드에서 실행하기 echo전에 mv모든 것이 잘 보이는지 확인하십시오 .

pps. 또한 sed 구성에서는 fdjskjfls가 한 줄에 있고 같은 줄에 이전에 태그가 없을 것으로 예상합니다.

답변2

GNU가 있다고 가정하면 더 간단한 접근 방식을 사용하겠습니다 grep.

for f in *.html ; do 
    mv -v "$f" "$(grep -oP '<title>\K.+?</title>' $f | sed 's#</title>##').html"
done

관련 정보