Bash

在 if 語句中將系統路徑與 awk 匹配

  • February 25, 2020

我試圖捕捉文件系統是否安裝在目錄樹上:

mount | awk '{ if ( $3 == /mnt/pxe ) print mounted }'

但是即使 mount 存在,字元串也不會被擷取。mount命令輸出為:

/home/olegs/infra/isos/test/archlinux-2020.02.01-x86_64.iso on /mnt/pxe type iso9660 (ro,relatime,nojoliet,check=s,map=n,blocksize=2048)

正則表達式匹配也不成功:

mount | grep pxe | awk '{ if ( $3 ~ /mnt/pxe ) print $3 }' 

不匹配

mount | grep pxe | awk '{ if ( $3 ~ .mnt.pxe ) print $3 }'
awk: cmd. line:1: { if ( $3 ~ .mnt.pxe ) print $3 }
awk: cmd. line:1:             ^ syntax error

mount | grep pxe | awk '{ if ( $3 ~ \/mnt\/pxe ) print $3 }'
awk: cmd. line:1: { if ( $3 ~ \/mnt\/pxe ) print $3 }
awk: cmd. line:1:             ^ backslash not last character on line
awk: cmd. line:1: { if ( $3 ~ \/mnt\/pxe ) print $3 }
awk: cmd. line:1:             ^ syntax error

請建議正確的語法以僅匹配該欄位/mnt/pxe的路徑。$3

您幾乎做對了,只需使用引號進行字元串比較:

mount | awk '{ if ( $3 == "/mnt/pxe" ) print "mounted" }'

請注意,“已安裝”也包含在引號中。

但是,如果您更喜歡使用正則表達式,請記住以斜線開頭和結尾:

mount | awk '{ if ( $3 ~ /.mnt.pxe/ ) print "mounted" }'
mount | awk '{ if ( $3 ~ /\/mnt\/pxe/ ) print "mounted" }'
mount | awk '{ if ( $3 ~ /^\/mnt\/pxe$/ ) print "mounted" }' #For exact match

引用自:https://unix.stackexchange.com/questions/569590