簡體   English   中英

如果與SED或AWK一起使用,如何使用?

[英]How to use if, else with SED or AWK?

我必須在文件的特定部分下插入幾行。 為此,我需要編寫一個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 

如果它在第一行之后是一個單節標題,則可以使用sed replace:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM