2015-09-16 14 views
5

Bên trong một vòng lặp đọc trong khi đọc, tôi thấy mở rộng biến này ${line/device name:}. Tôi đã thử chạy kịch bản với tập tin đầu vào của riêng tôi và nó chỉ in ra dòng.Mở rộng biến Bash với '/'

Bạn có thể cho tôi biết bản mở rộng đó đang hoạt động không?

+0

Cả hai câu trả lời là chính xác, nhưng đây là tài liệu về mở rộng tham số để tham khảo và chỉnh sửa sau này thành câu trả lời: http://www.gnu.org/software/bash/manual/html_node/ Shell-Parameter-Expansion.html –

Trả lời

4

Tên biến là line./là dành cho thay thế chuỗi, đó là "tên thiết bị:" nếu tồn tại ở bất kỳ đâu trong số $line bị xóa.

> line="a device name: some name" 
> echo ${line/device name:} 
a some name 

Bạn cũng có thể thấy #% thay thế, trong đó đại diện cho sự thay thế trong line bắt đầu và kết thúc. Ngoài ra hãy cẩn thận rằng việc thay thế / như vậy là một tính năng cụ thể (ví dụ: ash không hỗ trợ tính năng này, %# dường như di động), vì vậy bạn nên sử dụng #!/bin/bash thay vì #!/bin/sh làm băm đầu.

+0

'%' và '#' thực sự là di động, là [một phần của đặc tả shell POSIX] (http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06_02). – chepner

+0

Cảm ơn bạn. Câu trả lời tuyệt vời! – Jimbo

4

Nó trả về $line với chuỗi con device name: bị xóa. Từ trang bash man:

${parameter/pattern/string} 
     Pattern substitution. The pattern is expanded to produce a pattern just as in 
     pathname expansion. Parameter is expanded and the longest match of pattern against its value is replaced with string. If pattern begins with /, all 
     matches of pattern are replaced with string. Normally only the first match is 
     replaced. If pattern begins with #, it must match at the beginning of the 
     expanded value of parameter. If pattern begins with %, it must match at the 
     end of the expanded value of parameter. If string is null, matches of pattern are deleted and the/following pattern may be omitted. If parameter is @ or 
     *, the substitution operation is applied to each positional parameter in turn, 
     and the expansion is the resultant list. If parameter is an array variable 
     subscripted with @ or *, the substitution operation is applied to each member 
     of the array in turn, and the expansion is the resultant list. 
+0

Cảm ơn bạn. Câu trả lời tuyệt vời! – Jimbo

Các vấn đề liên quan