The awk function split(s,a,sep) splits a string s into an awk array a using the delimiter sep.
set time = 12:34:56
set hr = `echo $time | awk '{split($0,a,":" ); print a[1]}'` # = 12
set sec = `echo $time | awk '{split($0,a,":" ); print a[3]}'` # = 56
# = 12 34 56
set hms = `echo $time | awk '{split($0,a,":" ); print a[1], a[2], a[3]}'`
——————————————————————————————————————————
Q:
name="76868&5676&435&43526&334&12312312&12321"
awk 'BEGIN {print split("$name", filearray, "&")}'
為什麼是1
而
awk 'BEGIN {print split("76868&5676&435&43526&334&12312312&12321", filearray, "&")}'
則返回正確的結果,應該是7,有沒有人解答一下?
A:
變數引用錯誤,這樣做試試
awk 'BEGIN {print split('"\"$name\""', filearray, "&")}'
awk規定引用系統變數必須使用單引號加雙引號,即'"$sysvar"'這樣的格式,但是split函數也需要雙引號來定界,但這個雙引號又不能讓sh解釋,而應留給awk來解釋,所以使用了\"和\"組成的雙引號
split函數的用法
he awk function split(s,a,sep) splits a string s into an awk array a using the delimiter sep.
set time = 12:34:56
set hr = `echo $time | awk '{split($0,a,":" ); print a[1]}'` # = 12
set sec = `echo $time | awk '{split($0,a,":" ); print a[3]}'` # = 56
# = 12 34 56
set hms = `echo $time | awk '{split($0,a,":" ); print a[1], a[2], a[3]}'`
set hms = `echo $time | awk '{split($0,a,":" ); for (i=1; i<=3; i++) print a[i]}'`
執行個體一:
cat a
a:b:c:d:e:f:g:h:i
使用awk將該字串冒號兩邊的段輸出
cat a |awk -F':' '{split($0,arr,":")}END{for(i=1;i<=NF;i++)printf("%s\n",arr[i])}'
輸出結果如下
a
c
d
e
f
g
h
i