Line feed in the results of the shell script using grep command

I am writing a shell script to grep something from a log file and then print all the results using echo команда.

I could do that but suppose log contain more than 1 instance of the search string then it prints all the results in one line. Is it possible to print the results with line feed; if I simply execute the grep command in the shell then it will print with line feed so I thought with shell script also it will work same way but clearly that's not happening.

My shell scripts:

#!/bin/bash
messageStr='a senior leader of '$2
echo $messageStr
results=`grep "$messageStr" $1`
echo "results= " $results

Мой файл журнала:

A column written for ndtv.com by Ashutosh, a senior leader of Aam Aadmi Party or AAP, triggered protests from the opposition today and an order to appear before the country's top women's rights body, which said he has demeaned women.

a senior leader of Aam Aadmi Party or AAP

A column written for ndtv.com by Ashutosh, a senior leader of Aam Aadmi Party or AAP, triggered protests from the opposition today and an order to appear before the country's top women's rights body, which said he has demeaned women.

Фактические результаты:

results=  A column written for ndtv.com by Ashutosh, a senior leader of Aam Aadmi Party or AAP, triggered protests from the opposition today and an order to appear before the country's top women's rights body, which said he has demeaned women. a senior leader of Aam Aadmi Party or AAP

Ожидаемые результаты:

results=  A column written for ndtv.com by Ashutosh, a senior leader of Aam Aadmi Party or AAP, triggered protests from the opposition today and an order to appear before the country's top women's rights body, which said he has demeaned women. 
a senior leader of Aam Aadmi Party or AAP

Пожалуйста, дайте мне знать, если требуется какая-либо другая информация.

1 ответ

Решение

Переменные без кавычек подвергаются разделению слов (после раскрытия параметра оболочки пробелы, символы табуляции и символы новой строки используются для разделения расширенной переменной на отдельные аргументы) и глобализации (раскрытие подстановочных знаков оболочки). Как правило, вы должны всегда заключать двойные кавычки в переменные оболочки, если вы не хотите, чтобы слова были разделены и / или выделены. Для получения дополнительной информации см. http://mywiki.wooledge.org/Quotes

Если я правильно понимаю ваш вопрос, в этом случае вам просто нужно процитировать $results параметр:

messageStr="a senior leader of $2"
echo "$messageStr"
results=$(grep "$messageStr" "$1")
echo "results=  $results"

Кстати, использование обратных тиков (эффективно) не рекомендуется для подстановки команд; лучше всего использовать $(),

Приложение: http://shellcheck.net/ обеспечивает очень полезную обратную связь при разработке сценариев оболочки (например, выделение переменных без кавычек).

Другие вопросы по тегам