1

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

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

我在 Internet 上查找了信息,并使用了在 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"
4

1 回答 1

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
于 2013-06-25T03:03:57.313 回答