我正在嘗試使用 awk 在 bash 腳本中實作 startsWith 函式,但它不起作用。
https://www.gnu.org/software/gawk/manual/html_node/String-Functions.html
#! /bin/bash
starts_with()
{
local string=$1
local substring=$2
local index=$(printf "%s" "$string" | awk 'BEGIN { print index("$string", "$substring") }')
if [[ "$index" == "1" ]]
then
echo "true" : $string : $substring
else
echo "false" : $string : $substring
fi
}
starts_with key1="value" key1=
starts_with key2="value" wrong_key=
這是輸出:
false : key1=value : key1=
false : key2=value : wrong_key=
但是 awk 頁面說:
index(in, find)
Search the string in for the first occurrence of the string find, and return the position in characters where that occurrence begins in the string in. Consider the following example:
$ awk 'BEGIN { print index("peanut", "an") }'
-| 3
If find is not found, index() returns zero.
With BWK awk and gawk, it is a fatal error to use a regexp constant for find. Other implementations allow it, simply treating the regexp constant as an expression meaning ‘$0 ~ /regexp/’. (d.c.)
上述starts_with功能有什么問題以及如何解決?
uj5u.com熱心網友回復:
awk當您可以直接在 bash 中執行時,使用它沒有意義嗎?
#!/bin/bash
starts_with() {
local string="$1"
local substring="$2"
if [[ $string == "$substring"* ]]
then
echo "true : $string : $substring"
else
echo "false : $string : $substring"
fi
}
uj5u.com熱心網友回復:
awk 'BEGIN { print index("$string", "$substring") }'
您不能在 GNUAWK命令中使用這樣的 shell 變數考慮簡單的示例
string="HELLOWORLD" && awk 'BEGIN{print "$string"}' emptyfile.txt
輸出
$string
觀察$string出現的文字,例如,-v如果您想將浮動在 shell 中的變數 ram 放入 GNUAWK命令中,請使用
string="HELLOWORLD" && awk -v s=$string 'BEGIN{print s}' emptyfile.txt
輸出
HELLOWORLD
(在 GNU Awk 5.0.1 中測驗)
uj5u.com熱心網友回復:
如果您不介意額外輸入,則將其匯出:
export string="HELLOWORLD" && mawk '
BEGIN {
print ENVIRON["string"]
}'
HELLOWORLD
如果你不想出口,我想這也可以
% string2="HELLOWORLD" mawk '
BEGIN{
print ENVIRON["string2"]
}' | gtee >( gpaste - \
\
| gsed -zE 's/^/ orig from pipe :: /' >&2;) | gcat -n
1 HELLOWORLD
orig from pipe :: HELLOWORLD
我不知道 Linux 和其他人的剪貼板機制是如何作業的,但如果你碰巧是 on macOS,并且你想要引入的 shell 變數并不太復雜,這里有另一種方法:
pbcopy <<<"${TERM_SESSION_ID}" ;
mawk 'BEGIN {
(__=" pbpaste ") | getline _;
close(__)
print "pasting via macos clipboard ::", (_) }' | lgp3
pasting via macos clipboard :: BEC24EEE-B6B3-4862-A286-1953FB6438A7
如果你喜歡你getline的 s 是單一的陳述,那么也許
mawk ' BEGIN {
printf(" pasting via macos clipboard :: %*s",
close((__="pbpaste")|getline _)<"",_)
}' | lgp3
pasting via macos clipboard :: BEC24EEE-B6B3-4862-A286-1953FB6438A7
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/459788.html
