Linux裡awk中split函數的用法小結_linux shell

來源:互聯網
上載者:User

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

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.