AIX(KSH)动态变量赋值 - 将长字符串拆分为多行并将每行分配给变量

时间:2013-06-24 22:31:29

标签: shell ksh aix

在AIX(Korn Shell)上,我如何实现动态变量名生成和赋值?

我基本上有一个字符串为“LINE 1 LINE 2 LINE 3 LINE 4 LINE 5”,我希望将这个长字符串分成多行(每个7个字符长)并将其分配给动态生成的变量,如msg_txt_line_1, msg_txt_line_2等等。

我在互联网上查找信息并使用Building Dynamic Variable Names in KornShell的一些帮助我到目前为止构建了这个代码段,但它会出错。

foo.sh

TEXT='LINE 1 LINE 2 LINE 3 LINE 4 LINE 5'
counter=1
echo $TEXT | fmt -7 | while read line ; do eval msg_txt_line_$counter=$line;counter=$(( counter += 1 )) ; done
echo $msg_txt_line_1
echo $msg_txt_line_2
echo $msg_txt_line_3
echo $msg_txt_line_4
echo $msg_txt_line_5

错误是

AIX:>foo.sh
foo.sh[4]: 1:  not found.
foo.sh[4]: 2:  not found.
foo.sh[4]: 3:  not found.
foo.sh[4]: 4:  not found.
foo.sh[4]: 5:  not found.

感谢您的指导。


我一直在研究这个问题,并且在JS的评论中,我已经设法编写了以下脚本,它运行正常。这仍然可以改进,例如,如果长行包含诸如`,“,'和Shell特殊字符之类的字符?感谢有人可以帮我改进这个片段。

x=1
TEXT="No one is going to hand me success. I must go out & get it myself. That's why I'm here. To dominate. To conquer. Both the world, and myself."
echo "$TEXT" | fmt -30 | while IFS=$'\n' read -r line; do export msg_txt_line_$x="$line"; let "x=x+1";done
echo "$msg_txt_line_1"
echo "$msg_txt_line_2"
echo "$msg_txt_line_3"
echo "$msg_txt_line_4"
echo "$msg_txt_line_5"

1 个答案:

答案 0 :(得分:1)

您可以创建一个数组然后分配值。类似于:

$ TEXT='LINE 1 LINE 2 LINE 3 LINE 4 LINE 5'
$ echo "$TEXT" | fmt -w7 > myfile
$ while IFS=$'\n' read -r line; do export msg_txt_line_$((++x))="$line"; done <myfile
$ echo "$msg_txt_line_1"
LINE 1 

<击>

更新

$ TEXT='LINE 1 LINE 2 LINE 3 LINE 4 LINE 5'
$ echo "$TEXT" | fmt -w7 > myfile
$ while IFS=$'\n' read -r line; do export msg_txt_line_$((++x))="$line"; done <myfile
$ echo "$msg_txt_line_1"
LINE 1