【发布时间】:2022-08-06 03:18:33
【问题描述】:
建议是一个 bash 函数,只使用 awk 来分割字符串接受任何字符串作为分隔符和任何字符串作为输入.
问题:如何创建一个仅使用 awk 并接受任何字符串作为输入和分隔符的分割字符串的函数?
!!!问题的原因!!!使用 bash 命令进行字符串拆分有很多很多建议(参见这个示例),但它们都只在特定情况下有效,而不是根据我们的建议。
谢谢,善待! ???
建议是一个 bash 函数,只使用 awk 来分割字符串接受任何字符串作为分隔符和任何字符串作为输入.
问题:如何创建一个仅使用 awk 并接受任何字符串作为输入和分隔符的分割字符串的函数?
!!!问题的原因!!!使用 bash 命令进行字符串拆分有很多很多建议(参见这个示例),但它们都只在特定情况下有效,而不是根据我们的建议。
谢谢,善待! ???
有很多很多关于使用 bash 命令拆分字符串的建议,但它们都只在特定情况下工作,不接受任何字符串作为输入和分隔符.
下面的函数由我们创建,接受任何字符串作为输入和分隔符。?
功能
declare -a F_MASTER_SPLITTER_R=()
f_master_splitter() {
: 'Split a given string and returns an array.
Args:
F_MS_STR_TO_SPLIT (str): String to split.
F_MS_DELIMITER_P (Optional[str]): Delimiter used to split. If not informed
the split will be done by spaces.
Returns:
F_MASTER_SPLITTER_R (array): Array with the provided string separated by
the informed delimiter.
'
local F_MS_STR_TO_SPLIT="$1"
local F_MS_DELIMITER="$2"
if [ -z "$F_MS_DELIMITER_P" ] ; then
F_MS_DELIMITER_P=" "
fi
F_MASTER_SPLITTER_R=()
# NOTES: We export these variables to avoid problems with certain characters
# in "awk". By Questor
export F_MS_STR_TO_SPLIT F_MS_DELIMITER
f_ez_trap_add "unset F_MS_STR_TO_SPLIT F_MS_DELIMITER" SIGINT SIGTERM ERR EXIT
local F_MS_EVAL_ITEM=""
# NOTES:
# I - The strategy used consists of having each output resulting from the awk
# command array be converted into a native bash command to add each of these
# items to the F_MASTER_SPLITTER_R bash array. As this treatment exists, it is
# practically certain (the chance of error is very small) that each entry will
# be correctly converted to an entry of the bash array. This is because bash
# treats the output of a command as text and the fact that this function does
# this treatment is precisely what makes this approach better and safer than
# all others as a universal strategy for string splitting in bash;
# II - We replaced "HEREDOC" with "0EA41DB0533442FA9DF7E74E0D9E945E25AE7F1CE7E0460891104717436E4130"
# to make the possibility of conflict with "HEREDOC" almost null, that is, if
# an entry has the value "HEREDOC" inside it.
# By Questor
# [Ref(s).: https://stackoverflow.com/a/15787182/3223785 ,
# https://stackoverflow.com/a/26005804/3223785 ,
# https://unix.stackexchange.com/a/593216/61742 ,
# https://unix.stackexchange.com/a/353689/61742 ]
F_MS_EVAL_SPLIT=$(awk 'BEGIN {
n=split(ENVIRON["F_MS_STR_TO_SPLIT"], split_arr, ENVIRON["F_MS_DELIMITER"]);
for(i=1; i<=n; i++){
printf "read -r -d \047\047 F_MS_EVAL_ITEM << '0EA41DB0533442FA9DF7E74E0D9E945E25AE7F1CE7E0460891104717436E4130'\nBEGIN\n%sEND\n0EA41DB0533442FA9DF7E74E0D9E945E25AE7F1CE7E0460891104717436E4130\nF_MASTER_SPLITTER_R+=(\"${F_MS_EVAL_ITEM:6:-3}\")\n", split_arr[i]
}
}')
unset F_MS_STR_TO_SPLIT F_MS_DELIMITER
# NOTE: Process the entries for the F_MASTER_SPLITTER_R bash array. By Questor
eval "$F_MS_EVAL_SPLIT"
}
用法
f_master_splitter "<STR_INPUT>" "<STR_DELIMITER>"
笔记:这f_master_splitter以上作为该项目的一部分完全免费提供ez_i - Create shell script installers easily!。
【讨论】: