[英]How to cut an existing variable and assign to a new variable in bash
!/bin/bash
VAR=$(some curl commands)
token =$(cut -c 18-53 $VAR)
echo $token
我想在我的cut命令中使用VAR變量,但是當我這樣使用時,它說:
No such file or directory
我只是想將VAR(curl命令的輸出)從18.char削減到53.char。 有什么建議嗎?
讓我們定義一個示例var
:
$ var='The quick brown fox jumped over the lazy dog on the way to the market'
現在,使用cut
選擇18到53的字符:
$ echo $(cut -c 18-53 <<<"$var")
ox jumped over the lazy dog on the w
因為cut
期望從標准輸入(如果不是文件)中讀取內容,所以我們使用<<<
告訴bash在標准輸入上提供$var
的內容。 這稱為here字符串 。
另外,我們可以單獨使用bash選擇相同的字符:
$ echo ${var:17:36}
ox jumped over the lazy dog on the w
構造${var:17:36}
稱為子字符串擴展 。 它從位置17開始選擇36個字符。(在bash中,與cut
不同,第一個字符編號為零。)
當然,我們可以將選定的字符串分配給變量:
$ token=${var:17:36}
$ echo "$token"
ox jumped over the lazy dog on the w
要么:
$ token=$(cut -c 18-53 <<<"$var")
$ echo "$token"
ox jumped over the lazy dog on the w
上面的命令在bash中有效。 如果我們希望可移植到POSIX shell,那么我們既不能使用子字符串擴展,也不能在此處使用strings 。 相反,正如戈登·戴維森 ( Gordon Davisson)指出的那樣,我們可以使用:
$ echo "$var" | cut -c 18-53
ox jumped over the lazy dog on the w
要么:
$ token=$(echo "$var" | cut -c 18-53)
$ echo "$token"
ox jumped over the lazy dog on the w
gniourf_gniourf建議了另一種POSIX方法,該方法避免了外部過程:
$ printf '%.36s\n' "${var#?????????????????}"
ox jumped over the lazy dog on the w
cut
和bash子字符串擴展的比較 正如David C. Rankin在評論中指出的那樣,使用bash的內部字符串處理具有強大的優勢。 一種是使用bash的內部命令可以避免產生其他子shell和可執行文件。 如果在循環內生成其他子外殼,則這會極大地影響性能。
同樣,命令替換具有從其輸出中刪除尾隨換行符的副作用。 這可能會導致意外的意外。 使用bash的內部字符串處理可避免這種副作用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.