1

KS=$(locate acpi-support | grep "/etc/rc" | cut -f4 -d/ | tr -dc '[K,S]')
LEVELS=$(locate acpi-support | grep "/etc/rc" | cut -f3 -d/ | tr -dc '[0-9]')
echo $KS
echo $LEVELS

我得到以下输出:

KSSSS
12345

我想做的是以这种方式交替合并以前的输出:

K1 S2 S3 S4 S5

我尝试了嵌套for循环,但没有成功,我该怎么做?

4

5 回答 5

3

您可以使用 for 循环遍历其中一个字符串中的字符,然后使用 bash 的子字符串功能打印出字符。如下所示:

KS="KSSSS"
LEVELS="12345"
unset result
for (( i=0; i<${#KS}; i++ )); do
  result+="${KS:$i:1}${LEVELS:$i:1} "
done
echo "$result"

输出:

K1 S2 S3 S4 S5
于 2013-04-05T12:08:03.923 回答
1
$ KS=KSSSS

$ LEVELS=12345

$ awk '{n=length/2;for(i=1;i<=n;i++)print $i$(i+n)}' ORS=" " FS= <<< "$KS$LEVELS"
K1 S2 S3 S4 S5
于 2013-04-05T12:18:46.667 回答
1

Python 单线

$ KS="KSSSS"
$ LEVELS="12345"
$ python -c 'import sys; print " ".join([k+v for k,v in zip(sys.argv[1], sys.argv[2])])' $KS $LEVELS
K1 S2 S3 S4 S5
$
于 2013-04-05T15:47:26.450 回答
0

这应该有效:

KS="KSSSS"
LEVELS="12345"
for i in {0..4}; do
  echo ${KS:$i:1}${LEVELS:$i:1}
done

虽然可以肯定,awk大师会以更好的单线方式来拯救:)

要使其全部出现在同一行:

for i in {0..4}; do
  echo ${KS:$i:1}${LEVELS:$i:1} | awk '{printf("%s ",$1)}
done
于 2013-04-05T12:03:48.530 回答
-1

如果你制作KSLEVELS数组而不是字符串,你可以使用paste

KS=( $(locate acpi-support | grep "/etc/rc" | cut -f4 -d/ | tr -dc '[K,S]') )
LEVELS=( $(locate acpi-support | grep "/etc/rc" | cut -f3 -d/ | tr -dc '[0-9]') )

paste -d"\0" <( printf "%s\n" ${KS[@]}) <( printf "%s\n" ${LEVELS[@]})
于 2013-04-05T12:10:49.227 回答