如何在bash中迭代多行变量?
给定 相反,我得到了如何在bash中迭代多行变量?,bash,Bash,给定 相反,我得到了 thing1 this is thing1! thing2 this is thing2! 我做错了什么 我想阅读新行,这样我就可以在@上剪切,并相应地printf。#/bin/bash thing1thing2 this is thing1!this is thing2! 输入=”\nthing1@this这是第一件事\nthing2@this这是第二件事!” #echo用真正的新行替换“\n” #readarra
thing1 this is thing1!
thing2 this is thing2!
我做错了什么
我想阅读新行
,这样我就可以在@
上剪切
,并相应地printf
。#/bin/bash
thing1thing2 this is thing1!this is thing2!
输入=”\nthing1@this这是第一件事\nthing2@this这是第二件事!”
#echo用真正的新行替换“\n”
#readarray-t将多行字符串加载到数组中
readarray-t数组#/bin/bash
输入=”\nthing1@this这是第一件事\nthing2@this这是第二件事!”
#echo用真正的新行替换“\n”
#readarray-t将多行字符串加载到数组中
readarray-t array根据您的问题,当与here字符串一起使用时,bash似乎不会解释任何\n\t\f e.t.c
。这可能是您想要的,这可能是一种不好的做法。双引号周围的感叹号将导致错误,因为bash将尝试将其作为事件(某个点在shell上执行的命令)进行求值,因此必须转义(从终端使用时)
命令=”\nthing1@this事情是1\\nthing2@this这是第二件事!”
读行时;做
//在这里做你的事
行根据您的问题,当与here字符串一起使用时,bash似乎不会解释任何\n\t\f e.t.c
。这可能是您想要的,可能是不好的做法。双引号周围的感叹号将导致错误,因为bash将尝试将其作为事件(某个点在shell上执行的命令)进行求值,因此必须转义(从终端使用时)
命令=”\nthing1@this事情是1\\nthing2@this这是第二件事!”
读行时;做
//在这里做你的事
行如何echo“$commands”|awk-F@'{printf(“%20s\t%s\n”,$1,$2)}'
所有数据一个进程,而不是每行8个进程;-)。祝你好运。啊,我想应该是echo-e
。。。但是,是的,没有想到awk
。我不是bash大师,因此对每行滥用进程表示歉意:-o介意将您的解决方案作为答案发布吗?您是使用两个字符序列\`、
n`自动生成字符串,还是使用真正的换行符?一般来说,几乎没有理由这样使用cut
。让read使用为您进行解析,而IFS=@read-r cmd desc;do…
@rici Yes,请参见上面我代码中的注释:这是通过编程生成的
如何echo“$commands”| awk-F@'{printf(“%20s\t%s\n”,$1,$2)}'
所有数据一个进程,而不是每行8个进程;-)。祝你好运。啊,我想应该是echo-e
。。。但是,是的,没有想到awk
。我不是bash大师,因此对每行滥用进程表示歉意:-o介意将您的解决方案作为答案发布吗?您是使用两个字符序列\`、
n`自动生成字符串,还是使用真正的换行符?一般来说,几乎没有理由这样使用cut
。让read使用为您进行解析,而IFS=@read-r cmd desc;do…
@rici是的,请参见上面我的代码中的注释:这是通过编程生成的
请非常小心eval
。如果input
碰巧包含rm-rf/*
,该怎么办?你怎么到处走动-bash:\nthing2@this:未找到事件
?哇,我不明白。发布了我的整个脚本。没有单个引用input
,代码>是不允许的。(这可能是问题本身的输入错误)只需尝试input=”\nthing1@this这是第一件事\nthing2@this“这是第二件事!”;echo-e“$input”
然后对其单引号并重试。从bash
4.4开始,您可以使用${input@E}
代替$(echo-e“$input”)
。要非常小心eval
。如果input
碰巧包含rm-rf/*
,该怎么办?你怎么到处走动-bash:\nthing2@this:未找到事件
?哇,我不明白。发布了我的整个脚本。没有单个引用input
,代码>是不允许的。(这可能是问题本身的输入错误)只需尝试input=”\nthing1@this这是第一件事\nthing2@this“这是第二件事!”;echo-e“$input”
然后对其单引号并重试。从bash
4.4开始,您可以使用${input@E}
代替$(echo-e“$input”)
。
thing1thing2 this is thing1!this is thing2!
#!/bin/bash
input="\nthing1@this is thing 1!\nthing2@this is thing 2!"
# echo replaces '\n's with real new-lines
# readarray -t loads the multiline string into an array
readarray -t array <<< $(echo -e "${input}")
# loop it
for command in "${array[@]}"; do
echo "${command}"
done
commands="\nthing1@this is thing 1\!\nthing2@this is thing 2!"
while read line;do
// do your stuff here
line <<< $( echo -e "${commands}" ) # -e switch tells the echo command to honour all back slashes . The same behaviour can be achieved with `shopt -s xpg_echo` ( you have to remove -e switch whenever you do that )