如何在找到模式后读取文件内容?(unix)

时间:2017-04-28 07:51:41

标签: unix awk sed grep

我有一个包含一些带注释的文本的文件我必须将以特殊字符结尾的文本更改为其他内容而不更改任何注释

例如

------this is a comment1---
rose#
marigold#
------this is a comment2---
dog#
cat#
------pattern-------
------this is a comment3---
brazil
is awesome#
america#

我需要什么

1.寻找“-----模式----”从那里开始阅读

2.浏览评论

3.将字符串(重要)存储在变量中,直到找到“#”。如果字符串以元音开头,则为“$”。

4.保持直到文件结尾

我的最终文件应如下所示

------this is a comment1---
rose#
marigold#
------this is a comment2---
dog#
cat#
------pattern-------
------this is a comment3---
brazil
is awesome#
$america#

这是我试过的

awk '/----Pattern----/'{
while IFS="#" read -r LINE || [[ -n "$LINE" ]]; do
    if echo "$LINE" |grep -q '^--'; then
    continue
    else if echo "$LINE" |grep -q '^a'; then
       LINE="$""$LINE"

done

} file.txt

2 个答案:

答案 0 :(得分:1)

要从您输入的所有输入中发布的输出(使用GNU awk for multi-char RS)是:

new MaterialApp()

如果这不适合您的实际输入,请编辑您的问题,以提供更具真实代表性的样本输入和预期输出。

答案 1 :(得分:0)

在awk中

$ awk '
/pattern/ { f=1 }                       # flag up at pattern
f=="" || /^--.*--$/ { print; next }    # just print pre-flagged, comments and pattern
f { b=b (b==""?"":ORS) $0               # buffer after flag
    if(b~/#$/) {                        # once buffers ends with #
        print (b~/^[aeiouy]/?"$":"") b  # print buffer with $ where needed
        b=""                            # reset buffer
    }
}' file
...
------this is a comment3---
brazil
is awesome#
$america#