[英]How to split string across multiple lines in bash
對我來說,一個恆定的煩惱(次要但恆定)是我無法(或不知道如何)在bash代碼中將字符串拆分為多行。 我所擁有的是:
while getopts 'd:h' argv; do
case "${argv}" in
d) local target_dir="${OPTARG}" ;;
h)
printf "Usage: remove_file_end_strings [ -d <work directory> ] <string to remove>\n"
return 1
;;
esac
在這里看起來不錯,因為沒有自動換行,但是當限制在80個字符和自動換行時,看起來很不整潔。 當我想要的是這樣的東西時,在python或ruby中很簡單:
while getopts 'd:h' argv; do
case "${argv}" in
d) local target_dir="${OPTARG}" ;;
h)
printf "Usage: remove_file_end_strings [ -d <work "
"directory> ] <string to remove>\n"
return 1
;;
esac
我的google-fu讓我失望了,那么有沒有辦法以bash的方式實現這一目標,或者我只是不得不繼續努力地砍下一塊木頭? TA
編輯:我已經決定了我的次優解決方案:
while getopts 'd:h' argv; do
case "${argv}" in
d) local target_dir="${OPTARG}" ;;
h)
printf "Usage: remove_file_end_strings [ -d <work "
printf "directory> ] <string to remove>\n"
return 1
;;
esac
done
換行很容易,但是在縮進下一行時,不引入任何多余的空格或標記邊界比較困難。 沒有縮進,這很簡單但是很丑陋:
{
printf "Usage: remove_file_end_strings \
[ -d <work directory> ] <string to remove>\n"
}
不管好壞, echo
接受的內容都比較草率:
echo 'This is my string' \
'that is broken over' \
'multiple lines.'
這會將3個參數傳遞給echo而不是1,但由於參數之間用空格連接,因此效果相同。
在您的情況下,當您將整個消息放入格式字符串時,您可以模擬相同的行為:
printf "%b " 'This is my string' \
'that again is broken' \
'over multiple lines.\n'
雖然很明顯,當您使用具有不同插槽的正確格式字符串時,此方法效果不佳。
在這種情況下,會有一些駭客:
printf "I am also split `
`across %s `
`lines\\n" \
"a number of"
將內聯文檔與<<-
運算符一起使用:
while getopts 'd:h' argv; do
case "${argv}" in
d) local target_dir="${OPTARG}" ;;
h)
cat <<-EOT
Usage: remove_file_end_strings [ -d <work directory> ] <string to remove>
EOT
esac
done
參見man bash
並查找Here Documents
:
如果重定向運算符是<<-,則所有前導制表符將從輸入行和包含定界符的行中刪除。 這允許外殼腳本中的此處文檔以自然方式縮進。
如果需要換行,請用管道發送sed
命令,該命令將刪除字符串之間的制表符:
while getopts 'd:h' argv; do
case "${argv}" in
d) local target_dir="${OPTARG}" ;;
h)
cat <<-EOT | sed 's/\t*\([^\t]*\)/ \1/2g'
Usage: remove_file_end_strings [ -d <work \
directory> ] <string to remove>
EOT
esac
done
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.