Sri*_*att 3 linux bash variable text-formatting
我正在努力编写一个 bash 脚本,其中包含一个带有长字符串值的变量。当我将字符串分成多行时,它会抛出错误。如何将字符串拆分为多行并分配给变量?
Jef*_*ler 10
一个建议:
x='Lorem ipsum dolor sit amet, consectetur '\
'adipiscing elit, sed do eiusmod tempor '\
'incididunt ut labore et dolore magna aliqua.'
Run Code Online (Sandbox Code Playgroud)
其结果是预期的:
$ printf '%s\n' "$x"
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
Run Code Online (Sandbox Code Playgroud)
将长字符串分配为数组中的多个子字符串可以使代码更具美感:
#!/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
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
8707 次 |
最近记录: |