簡體   English   中英

BASH-從文本文件讀取多行

[英]BASH - Reading Multiple Lines from Text File

我正在嘗試讀取一個文本文件,例如file.txt,它包含多行。

file.txt的輸出是

$ cat file.txt
this is line 1

this is line 2

this is line 3

我想將整個輸出存儲為變量,例如$text
回顯變量$text ,預期輸出為:

this is line 1 this is line 2 this is line 3

我的代碼如下

while read line
do
    test="${LINE}"
done < file.txt

echo $test

我得到的輸出總是只有最后一行。 有沒有一種方法可以將file.txt中的多行連接為一個長字符串?

您可以將\\n (換行符)轉換為 (空間):

$ text=$(tr '\n' ' ' <file.txt)
$ echo $text
this is line 1 this is line 2 this is line 3

如果行以\\r\\n結尾,則可以執行以下操作:

$ text=$(tr -d '\r' <file.txt | tr '\n' ' ')

您必須將下一行的內容附加到變量中:

while read line
do
    test="${test} ${LINE}"
done < file.txt

echo $test

RESP。 甚至更簡單,您也可以一次將整個文件讀入變量:

test=$(cat file.txt)

RESP。

test=$(tr "\n" " " < file.txt)

如果您想保留換行符,它將很簡單:

test=<file.txt

另一個:

line=$(< file.txt)
line=${line//$'\n'/ }
test=$(cat file.txt | xargs)
echo $test

我相信這是最簡單的方法:

text=$(echo $(cat FILE))

但是它不會在單詞之間保留多個空格/制表符。

使用數組

#!/bin/bash

while read line
do
    a=( "${a[@]}" "$line" )
done < file.txt

echo -n "${a[@]}"

輸出:

this is line 1  this is line 2  this is line 3

參見例如關於陣列的tldp部分

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM