Bash-如何在sed命令输出中保留换行符?

Bash-如何在sed命令输出中保留换行符?,bash,sed,echo,delimiter,cat,Bash,Sed,Echo,Delimiter,Cat,假设我有一个文件BookDB.txt,它以以下格式存储数据: Harry Potter - The Half Blood Prince:J.K Rowling:40.30:10:50 The little Red Riding Hood:Dan Lin:40.80:20:10 Harry Potter - The Phoniex:J.K Rowling:50.00:30:20 Harry Potter - The Deathly Hollow:Dan Lin:55.00:33:790 Littl

假设我有一个文件BookDB.txt,它以以下格式存储数据:

Harry Potter - The Half Blood Prince:J.K Rowling:40.30:10:50
The little Red Riding Hood:Dan Lin:40.80:20:10
Harry Potter - The Phoniex:J.K Rowling:50.00:30:20
Harry Potter - The Deathly Hollow:Dan Lin:55.00:33:790
Little Prince:The Prince:15.00:188:9
Lord of The Ring:Johnny Dept:56.80:100:38
Three Little Pig:Andrew Lim:89.10:290:189
All About Linux:Ubuntu Team:76.00:44:144
Catch Me If You Can:Mary Ann:23.60:6:2
Python for dummies:Jared Loo:15.99:1:10
我正在尝试将输出中的(:)分隔符替换为(,)。它成功了,但从输出中删除了换行符。这是我的密码:

TITLE=Potter
OUTPUT=$(cat BookDB.txt | grep $TITLE)
OUTPUT1=$(sed 's/:/, /g' <<< $OUTPUT)
echo $OUTPUT1
但是,它看起来是这样的:

Harry Potter - The Half Blood Prince, J.K Rowling, 40.30, 10, 50
Harry Potter - The Phoniex, J.K Rowling. 50.00. 30. 20
Harry Potter - The Deathly Hollow, Dan Lin, 55.00, 33, 790
 Harry Potter - The Half Blood Prince, J.K Rowling, 40.30, 10, 50 Harry Potter - The Phoniex, J.K Rowling, 50.00, 30, 20 Harry Potter - The Deathly Holl
ow, Dan Lin, 55.00, 33, 790

如果有人能分享如何在输出中保留换行符,我将非常感激

您可以避免
cat
并在sed中执行所有操作:

sed -n '/Potter/s/:/, /gp' file
Harry Potter - The Half Blood Prince, J.K Rowling, 40.30, 10, 50
Harry Potter - The Phoniex, J.K Rowling, 50.00, 30, 20
Harry Potter - The Deathly Hollow, Dan Lin, 55.00, 33, 790

只需使用正确的报价:

TITLE=Potter
OUTPUT=$(cat BookDB.txt | grep $TITLE)
OUTPUT1=$(sed 's/:/, /g' <<< "$OUTPUT")
echo "$OUTPUT1"
TITLE=Potter
输出=$(cat BookDB.txt | grep$标题)

OUTPUT1=$(sed's/:/,/g'使用
awk
。匹配将特定于标题,不包括作者姓名

awk -F: -v OFS=', ' '$1 ~ /Potter/ { $1 = $1; print }' file
输出:

Harry Potter - The Half Blood Prince, J.K Rowling, 40.30, 10, 50
Harry Potter - The Phoniex, J.K Rowling, 50.00, 30, 20
Harry Potter - The Deathly Hollow, Dan Lin, 55.00, 33, 790
Harry Potter - The Half Blood Prince, J.K Rowling, 40.30, 10, 50
Harry Potter - The Phoniex, J.K Rowling, 50.00, 30, 20
这不会产生任何输出:

awk -F: -v OFS=', ' '$1 ~ /Rowling/ { $1 = $1; print }' file
但这将:

awk -F: -v OFS=', ' '$2 ~ /Rowling/ { $1 = $1; print }' file
输出:

Harry Potter - The Half Blood Prince, J.K Rowling, 40.30, 10, 50
Harry Potter - The Phoniex, J.K Rowling, 50.00, 30, 20
Harry Potter - The Deathly Hollow, Dan Lin, 55.00, 33, 790
Harry Potter - The Half Blood Prince, J.K Rowling, 40.30, 10, 50
Harry Potter - The Phoniex, J.K Rowling, 50.00, 30, 20
要与标题和作者匹配,您可以:

awk -F: -v OFS=', ' '$1 ~ /Potter/ && $2 ~ /Rowling/ { $1 = $1; print }' file
或匹配(如果有验证):

awk -F: -v OFS=', ' '$1 ~ /Potter/, $2 ~ /Rowling/ { $1 = $1; print }' file

+1但当然,你可以将其实质性地重构为
sed-n/$TITLE/s/:/,/gp“BookDB.txt
@tripleee确实如此。正如anubhava已经指出的那样,我只是强调了引用问题(这可能会在OP的代码中引起更多问题)