Bash - how to preserve newline in sed command output?

[亡魂溺海] 提交于 2019-12-01 18:22:21
Aserre

Just use correct quotation :

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

As \n is part of the default value of IFS, it is removed without the double quotes.

More info on quoting here

You can avoid cat and do all in 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

Using awk. Matching would be specific to the titles and doesn't include the author's name.

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

Output:

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

This gives no output:

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

But this will:

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

Output:

Harry Potter - The Half Blood Prince, J.K Rowling, 40.30, 10, 50
Harry Potter - The Phoniex, J.K Rowling, 50.00, 30, 20

To match against both title and author you can have:

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

Or to match if any validates:

awk -F: -v OFS=', ' '$1 ~ /Potter/, $2 ~ /Rowling/ { $1 = $1; print }' file
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!