elmazzun
elmazzun

Reputation: 1086

Alternate merge strings in BASH

From

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

I get the following outputs:

KSSSS
12345

What I'd like to do is to merge alternatively the previous outputs in this way:

K1 S2 S3 S4 S5

I tried whit nested for loops but without success, how could I do it?

Upvotes: 1

Views: 231

Answers (5)

rongenre
rongenre

Reputation: 1334

Python one-liner

$ 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
$

Upvotes: 1

Chris Seymour
Chris Seymour

Reputation: 85785

$ 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

Upvotes: 1

chepner
chepner

Reputation: 531075

If you make KS and LEVELS arrays instead of strings, you can use 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[@]})

Upvotes: -1

fedorqui
fedorqui

Reputation: 289625

This should work:

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

Although for sure awk guru will come to rescue with better one-liner way : )

To make it appear all on the same line:

for i in {0..4}; do
  echo ${KS:$i:1}${LEVELS:$i:1} | awk '{printf("%s ",$1)}
done

Upvotes: 0

dogbane
dogbane

Reputation: 274592

You can use a for loop to iterate over the characters in one of the strings and then use bash's substring functionality to print out characters. This is shown below:

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

Output:

K1 S2 S3 S4 S5

Upvotes: 3

Related Questions