开发者

Converting string to an array in bash with positional values

开发者 https://www.devze.com 2023-04-10 01:51 出处:网络
I tried to look through a lot of similar questions but I have a specific query. I have two or more sets of strings (space separated values). I want to loop through

I tried to look through a lot of similar questions but I have a specific query. I have two or more sets of strings (space separated values). I want to loop through

firstString="f1 f2 f3 f4"
secondString="s1 s2 s3 s4"

I want som开发者_开发技巧ething like

f1-s1
f2-s2
f3-s3
f4-s4

(in a single loop)

I must be able to take the positional value of the second and further arrays in a single loop.


Well, if you first replace all spaces with a new-line, using tr so that you have each value on a separate line, then paste will solve your problem:

$ cat a b
f1
f2
f3
f4
s1
s2
s3
s4

$ paste -d- a b
f1-s1
f2-s2
f3-s3
f4-s4

Pure bash solution:

#!/bin/bash

firstString='f1 f2 f3 f4'
secondString='s1 s2 s3 s4'

read -ra FIRST <<< "$firstString"
read -ra SECOND <<< "$secondString"

index=0
for i in ${FIRST[@]}
do
    echo $i-${SECOND[$index]}
    ((index++))
done


You could make use of bash built-in arrays:

first=(f1 f2 f3 f4)
second=(s1 s2 s3 s4)
for (( i = 0; i < ${#first[*]}; i++ )); do
    echo ${first[$i]}-${second[$i]}
done


see the test with awk below:

kent$  firstStr="f1 f2 f3 f4"
kent$  secondStr="s1 s2 s3 s4"

#now we have two variable


kent$  echo 1|awk -v two=$secondStr -v one=$firstStr '{split(one,a);split(two,b);for(i=1;i<=length(a);i++)print a[i]"-"b[i]}' 
f1-s1
f2-s2
f3-s3
f4-s4


You can easily do it in a portable manner:

set $firstString
for s in $secondString; do
  echo "$1-$s"
  shift
done
0

精彩评论

暂无评论...
验证码 换一张
取 消