将两个多行输出合并/合并为一个“ lineFromA:lineFromB”

时间:2018-06-20 23:39:01

标签: bash

输入2之1,

$ xinput list --id-only
2
4
12
3

输入2的2:

$ xinput list --name-only
Virtual core pointer
Virtual core XTEST pointer
SynPS/2 Synaptics TouchPad
Virtual core keyboard

预期输出:

2 : Virtual core pointer
4 : Virtual core XTEST pointer
12 : SynPS/2 Synaptics TouchPad
3 : Virtual core keyboard

我无法使用它。无论名称总是出现空格问题。

距离我很近:

SAVEIFS=$IFS
IFS=$'\n'
ids=($(xinput list --id-only))
names=($(xinput list --name-only))
combined=
for (( i=0; i<${#ids[@]}; i++ )); do
    temp=$(printf "%s %s $s\n" "${ids[i]}" $(echo "${names[i]}" | tr -d "\n" ) "${ids[i]}")
    combined="${combined} ${temp}"
done

echo "${combined}"
IFS=$SAVEIFS

输出:

$ ./touchpad 
 2 Virtual core pointer 
2   4 Virtual core XTEST pointer 
4   12 SynPS/2 Synaptics TouchPad 
12   3 Virtual core keyboard 
3   5 Virtual core XTEST keyboard 
5   

2 个答案:

答案 0 :(得分:2)

使用数组保存值。

#!/bin/bash
ids=()
names=()

while read id ; do
    ids+=("$id")
done < <(xinput list --id-only)

while read name ; do
    names+=("$name")
done < <(xinput list --name-only)

for ((i=0; i<${#ids[@]}; ++i)) ; do
    printf '%s: %s\n' "${ids[i]}" "${names[i]}"
done

您甚至可以使用paste直接合并输出:

paste <(xinput list --id-only) <(xinput list --name-only)

或使用它来填充关联数组:

#!/bin/bash
declare -A device

while read id name; do
    device[$id]=$name
done < <(paste <(xinput list --id-only) \
       <(xinput list --name-only))

for id in "${!device[@]}" ; do
    printf '%s: %s\n' "$id" "${device[$id]}"
done

答案 1 :(得分:0)

您还可以像这样利用paste

paste -d' : ' <(xinput list --id-only) /dev/null{,} <(xinput list --name-only)