我正在编写一个bash脚本,其中包含一个带有长字符串值的变量。当我将字符串拆分成多行时,它会抛出错误。如何将字符串拆分为多行并分配给变量?
发布于 2019-03-18 09:59:01
将长字符串赋值为数组中的多个子字符串可以使代码在美观上更具吸引力:
#!/bin/bash
text=(
'Contrary to popular'
'belief, Lorem Ipsum'
'is not simply'
'random text. It has'
'roots in a piece'
'of classical Latin'
'literature from 45'
'BC, making it over'
'2000 years old.'
)
# output one line per string in the array:
printf '%s\n' "${text[@]}"
# output all strings on a single line, delimited by space (first
# character of $IFS), and let "fmt" format it to 45 characters per line
printf '%s\n' "${text[*]}" | fmt -w 45要执行相反的操作,即取一长行,将其拆分为多行,并将其读入数组变量:
$ cat file
Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old.我们在这里使用fmt将行分解为最多30个字符的较短行,然后在bash shell中的readarray将这些行读入名为text的数组中:
$ readarray -t text < <(fmt -w 30 file)现在我们可以访问一组线路,或者每个单独的行:
$ printf '%s\n' "${text[@]}"
Contrary to popular belief,
Lorem Ipsum is not simply
random text. It has roots in a
piece of classical Latin
literature from 45 BC, making
it over 2000 years old.$ printf '%s\n' "${text[3]}"
piece of classical Latin(请注意,在bash中数组是基于零的。)
发布于 2019-02-28 15:31:54
一项建议是:
x='Lorem ipsum dolor sit amet, consectetur '\
'adipiscing elit, sed do eiusmod tempor '\
'incididunt ut labore et dolore magna aliqua.'预期的结果是:
$ printf '%s\n' "$x"
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.发布于 2019-02-28 17:52:34
假设您希望将字符串some long piece of text to assign分配给变量str。这不管用:
str='some long'
'piece of text'
'to assign'它将尝试在第一个命令之后运行行,您可能会得到“命令未找到”错误。
您可以这样做,但是换行符将嵌入到变量中,所以它不会是一行:
str='some long
piece of text
to assign'尽管您可以使用子字符串替换扩展(在Bash、ksh、zsh中)来替换它们,例如str="${str//来执行替换,并将新值保存在相同的变量中。注意,除了最后一行之外,所有后面的空格都将留在字符串中。
另一个选项是使用+=追加变量的值(也是Bash、ksh、zsh ):
str='some long'
str+=' piece of text'
str+=' to assign'在这里,任何空格都需要在引号中手动输入。
或者,类似地,在标准外壳中:
str='some long'
str="$str"' piece of text'
str="$str"' to assign'还有一种使用行延续的方法(杰夫在他们的回答中已经提到过):
str='some long'\
' piece of text'\
' to assign'在这里,尾随空格也很重要,只有当反斜杠后面紧跟换行符时行继续才能工作,而不是在中间有空格的情况下。
\n'/ }"来执行替换,并将新值保存在相同的变量中。注意,除了最后一行之外,所有后面的空格都将留在字符串中。
另一个选项是使用D5追加变量的值(也是Bash、ksh、zsh ):
A6
在这里,任何空格都需要在引号中手动输入。
或者,类似地,在标准外壳中:
A7
还有一种使用行延续的方法(杰夫在C8中已经提到过):
A9
在这里,尾随空格也很重要,只有当反斜杠后面紧跟换行符时行继续才能工作,而不是在中间有空格的情况下。
https://unix.stackexchange.com/questions/503572
复制相似问题