在ash中如何将多行输出设置为变量 编辑#3:我的问题已经关闭,并标记为duplicate,我无法关注我在这里发布是因为我正在寻求帮助:

问题描述

编辑#3:我的问题已经关闭,并标记duplicate,我无法关注。我在这里发布是因为我正在寻求帮助:(

enter image description here

我熟悉分批处理这种类型的事情,但无法弄清楚如何用灰烬做这件事(编辑: ash 不是bash )。 我正在搜索/etc/config/wireless设置的openwrt配置文件wifi-iface

到目前为止,我可以获得所需的输出

root@OpenWrt:~# awk '/wifi-iface/ {print $3}' /etc/config/wireless | sed s/\'//g
default_radio0
default_radio1
wifinet1

我的问题是如何像使用for f循环那样将此输出转换为变量?

编辑#1:类似

root@OpenWrt:~# echo $a
default_radio0

root@OpenWrt:~# echo $b
default_radio1

root@OpenWrt:~# echo $c
wifinet1

编辑#2:我猜我需要将输出从行更改为字符串:

root@OpenWrt:~# awk '/wifi-iface/ {print $3}' /etc/config/wireless | sed s/\'//g
 | xargs
default_radio0 default_radio1 wifinet1

距离越来越近,但是for循环如何工作?

解决方法

您可以使用malloc/morecore.c构造将命令的输出捕获到变量中:

    int Assign(int pos,node *p) {
       p->pos = pos;
       for(node *child : p->children)
         pos = Assign(pos,child);
       return pos + 1;
    }

使用数组的替代方法(评估起来会更安全):

$(command)
,

将此输出转换为变量,例如使用for f循环?

那么另一个答案的第一个代码段就足够了。

如何将多行输出设置为变量

通常,将整个输出保存在某个地方。从那里,提取一行,一次提取一行,然后根据需要分配给变量。一种更带壳的方法是在管道中解析数据,而不用将其存储在任何地方。

我正在尝试设置三个变量$ a $ b $ c

使用临时文件和read的POSIX方式:

tmpf=$(mktemp)
awk '/wifi-iface/ {print $3}' /etc/config/wireless | sed s/\'//g > "$tmpf"
{
   # read three lines of input
    IFS= read -r a
    IFS= read -r b
    IFS= read -r c
} < "$tmpf"
rm "$tmpf"

但没有临时文件,您可以调用三个进程来提取行:

tmp=$(awk '/wifi-iface/ {print $3}' /etc/config/wireless | sed s/\'//g)
a=$(printf "%s\n" "$tmp" | sed '1!d')
b=$(printf "%s\n" "$tmp" | sed '2!d')
c=$(printf "%s\n" "$tmp" | sed '3!d')

或者用制表符分隔的内容可能更清晰:

tmp=$(awk '/wifi-iface/ {print $3}' /etc/config/wireless | sed s/\'//g | paste -s)
a=$(printf "%s\n" "$tmp" | cut -f1)
b=$(printf "%s\n" "$tmp" | cut -f2)
c=$(printf "%s\n" "$tmp" | cut -f3)

我猜我需要将输出从行更改为字符串:

线是字符串。

有没有办法读取从第1行到x的所有行?

请不要删除特定范围内的行。

x=50; 
... | sed "1,$x!d"
,

感谢您的帮助@ dash-o和@KamilCuk,我终于设法弄清楚该怎么做:

#!/bin/sh

function list_wifi {
wifi=$(awk '/wifi-iface/ {print $3}' /etc/config/wireless | sed s/\'//g)

count=0 && for string in $wifi
  do
    eval ap$((++count))=$string
  done

ap=$(echo "$wifi" | wc -l)
  if [[ $ap -eq 1 ]];
    then
      echo next_function
    else
      echo "--Multiple APs detected"
  fi

count=0 && for string in $wifi
  do
    echo $((++count))-$string
  done

x=0 && while [[ $x -lt 1 || $x -gt $ap ]]
  do
    printf "--Select AP to clone (1-$ap): "
    read x
  done
}

结果:

root@OpenWrt:~# sh test
--Multiple APs detected
1-default_radio0
2-default_radio1
3-wifinet1
--Select AP to clone (1-3):

带有变量:

echo $ap1
default_radio0
echo $ap2
default_radio1
echo $ap3
wifinet1