Unix shell 脚本:将文件中的值分配给 while 循环中的变量,并在循环外使用该值
我正在编写一个 shell 脚本,我必须在其中提取以下类型的文件的内容:
类型1|值A
类型2|值B
类型1|值C
类型2|值D
类型3|值E
....
类型n|值Z。
对于 column_1
中的每种类型,我都有一个目标变量,它将相同类型的值连接起来,以获得如下结果:
var1=值A,值C
var2=值B,值D
var3=值E
......
脚本实现了这样的东西:
var1="HELLO"
var2="WORLD"
...
cat $file | while read record; do
#estract column_1 and column_2 from $record
if [ $column_1 = "tipo1" ]; then
var1="$var1, column_2" ## column_2 = valueB
elif ....
....
fi
done
但是当我尝试使用链接column_2
的任何变量的值时:
echo "$var1 - $var2"
我得到原始值:
HELLO - WORLD.
搜索互联网,我读到问题与管道创建一个复制实际值的子 shell 相关。
有办法解决这个问题吗!
最重要的是,有一种方法适合所有类型的 shell,事实上,这个脚本必须在不同的 shell 上运行!? 我不想使用文件支持来写入部分结果。
I'm writing a shell script, where I have to extract the contents of a file which is of type:
type1|valueA
type2|valueB
type1|valueC
type2|valueD
type3|valueE
....
typen|valueZ.
For each type in column_1
, I have a target variable, which concatenates the values of the same type, to get a result like this:
var1=valueA,valueC
var2=valueB,valueD
var3=valueE
.....
Script implements something like this:
var1="HELLO"
var2="WORLD"
...
cat $file | while read record; do
#estract column_1 and column_2 from $record
if [ $column_1 = "tipo1" ]; then
var1="$var1, column_2" ## column_2 = valueB
elif ....
....
fi
done
But when I try to use the value of any of the variables where I chained column_2
:
echo "$var1 - $var2"
I get the original values:
HELLO - WORLD.
Searching the internet, I read that the problem is related to the fact that the pipeline creates a subshell where the actual values are copied.
Is there a way to solve this problem!?
Above all, there is a way that would fit for all types of shells, in fact, this script must run potentially on different shells!?
I do not want to use file support on which to write the partial results.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您不需要使用
cat
。将某些内容通过管道传送到while
中会创建一个子 shell。当子 shell 退出时,循环中设置的变量值将丢失(另一个示例是使用cd
进行目录更改。相反,您应该将文件重定向到done:
顺便说一下,
你可以这样做:
You don't need to use
cat
. Piping something intowhile
creates a subshell. When the subshell exits, the values of variables set in the loop are lost (as would be directory changes usingcd
as another example. Instead, you should redirect your file into thedone
:By the way, instead of:
you can do:
BASH 常见问题解答条目 #24:“我在循环中设置变量。为什么它们在循环终止后突然消失?或者,为什么我不能通过管道读取数据?”
BASH FAQ entry #24: "I set variables in a loop. Why do they suddenly disappear after the loop terminates? Or, why can't I pipe data to read?"
内线:
Oneliner:
使用 awk
Using awk