请参阅下面的更新。
我正在尝试强制更新一些日语电子邮件文件的代码页。这些文件被标记为 UTF-8,但日语文本无法正确表示。我需要将 header 中的编码从“UTF-8”更改为“shift-jis”。
我已经手动检查了这个工作,但我想自动化这个过程。 使用两个 sed 命令:
#sed -i 's/charset="shift-jis"/charset="shift-jis"/g' $VariableForLine
#sed -i 's/?UTF-8?/?shift-jis?/g' $VariableForLine
我相信我可以做出所需的改变。 由于电子邮件的内容,我需要将其限制为仅更改电子邮件的标题。我认为标准的格式如下:
From: "=?UTF-8?Q?JapaneseNameEncodedIncorreclty" <<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="701f1e1f5e1b1f1a301a001d5e131f1d" rel="noreferrer noopener nofollow">[email protected]</a>>
To: "Yoshi Endo"
Subject: =?UTF-8?Q?????????????????=view=?UTF-8?Q????????????????
MIME-Version: 1.0
Date: Wed, 20 Feb 2006 10:30:22 0100
Content-Type: multipart/alternative;boundary="Next_Item:_(A3CB49KFSA19)/1"
This is a multi-part message in MIME format.
--Next_Item:_(A3CB49KFSA19)/1
Content-type: text/plain; charset="UTF-8"
?UTF-8?(example to skip)
Ÿž=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-Ÿž
Japanese Content
Ÿž=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-Ÿž
?UTF-8? (example to skip)
ここには、ログインしてください
----------------------------------------------------------------
Mixed content
***************************************************************************
Mixed content
***************************************************************************
--Next_Item:_(A3CB4g7FSA19)/1--
在文件上循环运行上述两个命令似乎可行,但我需要确保只有文件头和后面的字符集变量因其余电子邮件的内容而改变。
我制作的伪代码如下:
for each file in directory of type eml
do
read file line by line
if line contains "charset=" replace with ??
break
else
if line contains ?UTF-8?
replace ?UTF-8? with ?shift-jis'
exit
if 语句中第一个子句的进一步问题是“charset=”字符串可能没有应用编码,它可能是 UTF-8 或 ANSI,所以我需要搜索 charset= 的第一个实例,然后更改字符串以添加或替换后面的“”内的字符。
我目前遇到问题的代码如下所示(请原谅我对语法的掌握不佳)
#!/bin/bash
for file in ./*
do
cat $file | while read myline
do
if $myline |grep "charset="
then
echo $myline
#echo $myline #this prints all the content
fi
done
#sed -i 's/charset="shift-jis"/charset="shift-jis"/g' $LINE
#sed -i 's/?UTF-8?/?shift-jis?/g' $LINE
done #end
感谢您到目前为止的所有投入。非常感激。
编辑:我有一个解决方案
for file in `find ./ | grep .EML`
do
sed -i 's/charset=".*"/charset="shift-jis"/' $file
sed -i 's/?UTF-8?/?shift-jis?/' $file
done
IT 不会考虑 header ,但如果电子邮件中没有 charset= 代码的其他实例,那么应该没问题。
最佳答案
这符合你的要求吗?
sed '0,/charset=/s/old/new/' $file
这会将替换应用于从开头开始的每一行,直到并包括符合您的条件的第一行。该行之后,不再应用替换,其最终效果是仅修改与您的条件匹配的第一行。
关于string - 对于每个文件 : Walk line by line and grep for string (incorrect output),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10624557/