簡體   English   中英

Bash sed將字符串與上下換行符匹配

[英]Bash sed match a string with newlines above and below

這是一個文本文件的摘錄。

http_server = Server(
    uuid = "9a44b850-c54f-11e3-9c1a-0800200c9a66",
)

# https_server = Server(
#     uuid = "0c9cb0c0-c55e-11e3-9c1a-0800200c9a66",
# )

我想使用sed(或類似方法)從文件中提取“ 0c9cb0c0-c55e-11e3-9c1a-0800200c9a66”。

我已經嘗試過cat server.conf | sed -n 's/.*uuid = "\\(.*\\)",/\\1/p' cat server.conf | sed -n 's/.*uuid = "\\(.*\\)",/\\1/p'但這給了我兩個uuid。 當我輸入\\n之類的換行符時,sed根本不起作用。

uuid的唯一標記是https_server ,正則表達式必須確保uuid位於https_server

嘗試以下方法:

cat server.conf | sed -n -e '/https_server/{N;p}' | sed -n -e 's/.*uuid = "\([^ ]*\)",/\1/p'

或此調用sed僅一次:

cat server.conf | sed -n -e '/https_server/{N;s/.*uuid = "\([^ ]*\)",/\1/p}'

或者,如果塊內的https_server和uuid行之間有多個空行:

cat server.conf | sed -n -e '/https_server/,/uuid/p' | sed -n -e 's/.*uuid = "\([^ ]*\)",/\1/p'

為了確保uuidhttps_server內部,您可以跳過所有行,直到到達該字符串:

cat server.conf | sed -n '/https_server/,//{//!p}' | sed -n 's/.*uuid = "\(.*\)",/\1/p'

此代碼查找可能被注釋掉的https_server行,然后https_server一個https_server括號之前的塊中提取所有uuid

sed -n '/^#* *https_server *=.*(/,/)/!d;/^#* *uuid *= *"/!d;s///;s/",//p' searver.conf

這樣可以避免不必要地使用cat以及愚蠢的多重sed調用。

/regex/,/regex/

選擇一個區域。 動作!d只是丟棄該區域之外的任何行。

/^ *uuid *= *"/

選擇與該模式匹配的區域中的任何行。 同樣, !d丟棄任何未選擇的行。

s///

刪除以前匹配的模式。

最后,

s/",//

刪除字符串末尾的引號和逗號。

某些sed方言可能希望您在反義括號內加反斜杠。

這可能對您有用(GNU sed):

sed -rn '/https_server/{n;s/.*uuid = "([^"]*)".*/\1/p;q}' server.conf

如果uuid不在下一行,而是在下一行,請使用:

sed -rn '/https_server/{:a;n;/\)\s*$/b;s/.*uuid = "([^"]*)".*/\1/p;Ta;q}' server.conf

暫無
暫無

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

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