Bash 中的多行字串
-
在 Bash 中使用
here-document製作多行字串 - 在 Bash 中使用 Shell 變數製作多行字串
-
在 Bash 中使用
printf製作多行字串 -
在 Bash 中使用
echo和-e選項製作多行字串 -
在 Bash 中使用
echo製作多行字串
本教程演示了使用 here-document、shell 變數、printf、echo 和 echo 在 bash 中將多行字串列印到檔案的不同方法,而無需放置額外的空格(縮排) -e 選項。
在 Bash 中使用 here-document 製作多行字串
Here-document 提供了一種將多行字串輸入到檔案中的互動方式。EOF 被稱為 Here Tag。Here Tag 告訴 shell 你將輸入一個多行字串直到 Here Tag,因為它充當分隔符。<< 用於設定 Here Tag。> 用於輸入重定向。在我們的例子中,它將輸入重定向到指定的檔案 output.txt。
cat << EOF > output.txt
> Hello
> World
> !
> EOF
讓我們用 cat 命令檢查 output.txt 檔案的內容。
cat output.txt
從輸出中,我們看到每組單詞都有自己的一行,並且沒有多餘的空格。
Hello
World
!
在 Bash 中使用 Shell 變數製作多行字串
在這裡,我們使用了一個名為 greet 的 shell 變數。我們為 greet 分配了一個多行字串。
greet="Hello
> ,
> wolrd
> !"
下面的命令獲取 shell 變數 greet 中的多行字串,並使用 > 將其重定向到指定的檔案 multiline.txt。
echo "$greet" > multiline.txt
使用 cat 命令檢查 multiline.txt 的內容。
cat multiline.txt
從輸出中,我們看到每組單詞都有自己的一行,並且沒有多餘的空格。
Hello
,
wolrd
!
在 Bash 中使用 printf 製作多行字串
我們可以使用 printf 和換行符,並使用 > 將輸出重定向到檔案。檔案中的內容沒有多餘的空格。
#!/bin/bash
printf "Every word is on a seperate line!\n"
printf "%s\n" "Hello" "," "World" "!" > multiline.txt
輸出:
Every word is on a separate line!
使用 cat 命令列印出 multiline.txt 的內容。
cat multiline.txt
從輸出中,我們看到每組單詞都有自己的一行,並且沒有多餘的空格。
Hello
,
World
!
在 Bash 中使用 echo 和 -e 選項製作多行字串
以下 bash 指令碼將單詞列印到 multiline.txt,沒有任何額外的空格。-e 選項可以解釋變數 greet 中的轉義字元。
#!/bin/bash
greet="Hello\n,\nWorld\n!"
echo -e $greet > multiline.txt
使用 cat 命令列印出 multiline.txt 的內容
cat multiline.txt
從輸出中,我們看到每組單詞都有自己的一行,並且沒有多餘的空格。
Hello
,
World
!
在 Bash 中使用 echo 製作多行字串
下面的指令碼將一個多行字串分配給名為 greet 的變數。接下來,使用 > 將變數的內容重定向到 multiline.txt 檔案。greet 變數上的引號保留了新行。
#!/bin/bash
greet="Hello
,
World
!"
echo "$greet" > multiline.txt
使用 cat 命令顯示 multiline.txt 的內容。
cat multiline.txt
從輸出中,我們看到每組單詞都有自己的一行,並且沒有多餘的空格。
Hello
,
World
!
