bash awk 将字符串拆分为数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19606816/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-10 00:22:16  来源:igfitidea点击:

bash awk split string into array

bash

提问by Neon Flash

I am using awk to split a string into array using a specific delimiter. Now, I want to perform some operation on each element of the array.

我正在使用 awk 使用特定的分隔符将字符串拆分为数组。现在,我想对数组的每个元素执行一些操作。

I am able to extract a single element like this:

我能够提取这样的单个元素:

#! /bin/bash

b=12:34:56
a=`echo $b | awk '{split(
#! /bin/bash

b=12:34:56
`echo $b | awk '{split(
b=12:34:56
for element in ${b//:/ } ; do
  echo $element
done
,numbers,":");}'` for(i=0;i<length(numbers);i++) { // perform some operation using numbers[i] }
,numbers,":"); print numbers[1]}'` echo $a

I want to do something like this:

我想做这样的事情:

echo 12:34:56 | awk '{split(
b=12:34:56
IFS=:
set -- $b
for i; do echo $i; done
,numbers,":")} END {for(n in numbers){ print numbers[n] }}'

how would I do something like this in bash scripting?

我将如何在 bash 脚本中做这样的事情?

回答by Mat

You don't really need awk for that, bash can do some string processing all by itself.

你真的不需要 awk,bash 可以自己做一些字符串处理。

Try:

尝试:

IFS=: read -a numbers <<< "$b"

If you need a counter, it's pretty trivial to add that.

如果你需要一个计数器,添加它是非常简单的。

See How do I do string manipulations in bash?for more info on what you can do directly in bash.

请参阅如何在 bash 中进行字符串操作?有关您可以直接在 bash 中执行的操作的更多信息。

回答by Mat

None of these answers used awk (weird). With awk you can do something like:

这些答案都没有使用 awk(奇怪)。使用 awk,您可以执行以下操作:

echo "Hours: ${numbers[0]}"
echo "Minutes: ${numbers[1]}"
echo "Seconds: ${numbers[2]}"

for val in "${numbers[@]}"; do
   seconds=$(( seconds * 60 + $val ))
done

replacing print numbers[n]with whatever it is you want to do.

替换print numbers[n]为您想做的任何事情。

回答by ensc

b=12:34:56

# USE IFS for splitting (and elements can have spaces in them)
IFS=":"
declare -a elements=( $b )
#show contents
for (( i=0 ; i < ${#elements[@]}; i++ )); do
    echo "$i= ${elements[$i]}"
done

This does not contain bashisms but works with every sh.

这不包含 bashisms 但适用于每个 sh。

回答by chepner

The bashread command can split a string into an array by itself:

bash读命令可以在字符串分割成由本身的数组:

##代码##

To see that it worked:

要查看它是否有效:

##代码##

回答by vkersten

Another neat way, not using awk, but build-in 'declare':

另一种巧妙的方法,不是使用 awk,而是内置的“声明”:

##代码##