如何使用,否则使用SED或AWK?

时间:2015-12-04 23:45:00

标签: linux shell awk sed centos

我必须在文件的特定部分下插入几行。为此,我需要编写一个shell脚本。问题是文件中可能存在或不存在特定部分。 如果文件中没有[oslo_concurrency]部分,它应该首先在文件的末尾插入[oslo_concurrency],并且应该在[oslo_concurrency]部分下面添加'lock_path = / var / lock / cinder'行。如果[oslo_concurrency]部分存在,它应该只是[oslo_concurrency]部分下面的'lock_path = / var / lock / cinder'行。

我是否可以使用SED或AWK完成此任务,如果没有最简单的方法。请指导我完成这个场景。

输出文件看起来像。

[oslo_concurrency]
lock_path = /var/lock/cinder 

1 个答案:

答案 0 :(得分:1)

如果在第一行之后是单行部分标题,则可以使用sed替换:

file: test.txt

test data 1
test data 2
[oslo_concurrency]
test data 3
test data 4
test data 5
test data 6
test data 7
test data 8
test data 9
test data 10


function print_header() { 
cat << EOF
lock_path = /var/lock/cinder 
$(date '+%B %d, %Y @ ~ %r')  ID:$RANDOM
EOF
}

echo "$(print_header)" | sed '/\[oslo_concurrency\]/r/dev/stdin' test.txt

结果:

    test data 1
    test data 2
    [oslo_concurrency]
lock_path = /var/lock/cinder 
December 05, 2015 @ ~ 01:31:57 AM  ID:3115
    test data 3
    test data 4
    test data 5
    test data 6
    test data 7
    test data 8
    test data 9
    test data 10