2 回答

TA貢獻1895條經(jīng)驗 獲得超3個贊
一線解決方案sed:
MYVAR=$(sed -nE 's/^BAZ\s*=\s*(\S*)$/\1/p' inputfile)
如一條注釋中所述,sed在以下情況下,此命令將不會產(chǎn)生預(yù)期的結(jié)果:
BAZ = 10 // some comment ending with 0
此處MYVAR將分配0而不是10。要解決此問題,可以將正則表達式更改為:
MYVAR=$(sed -nE 's/^BAZ\s*=\s*([^\s\/]*).*/\1/p' inputfile)
現(xiàn)在MYVAR是10根據(jù)需要。分解正則表達式:
^BAZ\s*=\s*([^\s\/]*).*/\1
^ Match beginning of line
BAZ Match BAZ
\s*=\s* Match equal sign surrounded by zero or more spaces
([^\s\/]*) Capture in Group 1 any character that is not space or slash
.* Match the rest of the text
/\1 Replace matched text with text in Group 1
添加回答
舉報