使用带有for循环的sed从文本文件中删除行

时间:2014-04-08 04:44:32

标签: bash for-loop sed

我基本上尝试使用sed删除文本文档中的几行。要清理它。但我根本没有把它弄好。缺少什么,我不知道是什么......

#!/bin/bash

items[0]='X-Received:'
items[1]='Path:'
items[2]='NNTP-Posting-Date:'
items[3]='Organization:'
items[4]='MIME-Version:'
items[5]='References:'
items[6]='In-Reply-To:'
items[7]='Message-ID:'
items[8]='Lines:'
items[9]='X-Trace:'
items[10]='X-Complaints-To:'
items[11]='X-DMCA-Complaints-To:'
items[12]='X-Abuse-and-DMCA-Info:'
items[13]='X-Postfilter:'
items[14]='Bytes:'
items[15]='X-Original-Bytes:'
items[16]='Content-Type:'
items[17]='Content-Transfer-Encoding:'
items[18]='Xref:'

for f in "${items[@]}"; do
    sed '/${f}/d' "$1"
done

我在想,似乎是错误的,我可以设置一个for循环来检查数组中我想要从文本文件中删除的每个项目。但它根本不起作用。任何的想法。当然这是基本而简单的,但我无法弄清楚。

谢谢,

马立克

1 个答案:

答案 0 :(得分:2)

创建单个sed脚本要好得多,而不是按顺序生成19个小脚本。

幸运的是,通过加入数组元素生成脚本是Bash中的moderately easy

regex=$(printf '\|%s' "${items[@]}")
regex=${regex#'\|'}

sed "/^$regex/d" "$1"

(另请注意在最终正则表达式中添加^ - 我假设您只想在行首开始匹配。)

正确地说,你不应该删除邮件正文中的任何行,所以脚本应该在第一个空行之后留下任何内容:

sed "1,/^\$/!b;/$regex/d" "$1"

如果您想要就地编辑目标文件,请添加-i

相关问题