LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   How do I add tabs to multiple lines of text? (https://www.linuxquestions.org/questions/linux-newbie-8/how-do-i-add-tabs-to-multiple-lines-of-text-915490/)

diamonty 11-25-2011 07:50 AM

How do I add tabs to multiple lines of text?
 
Hi
I have a very simple script to see if NTP is installed:

NTP=$(rpm -qa | grep ntp)
echo "$NTP"

The output is:
ntp-4.2.4p8-2.el6.i686
fontpackages-filesystem-1.41-1.1.el6.noarch
ntpdate-4.2.4p8-2.el6.i686

How can I get this output to tab all 3 lines so that it looks like this:
ntp-4.2.4p8-2.el6.i686
fontpackages-filesystem-1.41-1.1.el6.noarch
ntpdate-4.2.4p8-2.el6.i686

I have tried playing around with the /t option but it only tabs the 1st line, the same with using /t in the printf command, would anyone have done something like this before?
Thanks

diamonty 11-25-2011 07:52 AM

The text under:
How can I get this output to tab all 3 lines so that it looks like this:

should have come out indented, ie with a tab, but the space must have been automatically removed...

sycamorex 11-25-2011 08:00 AM

Hi and welcome to LQ.

To correctly display your code preserving any formatting please wrap it in the CODE tags.

It'll make it more readable.

David the H. 11-25-2011 09:38 AM

First, the direct solution:

Code:

echo "$NTP" | sed 's/^/\t/'
Or an in-bash solution using parameter substitution with $'' (ansi-c style quoting):

Code:

echo $'\t'"${NTP//$'\n'/$'\n\t'}"
You might possibly need to enable shopt -s extquote first.

Or with printf:
Code:

IFS=$'\n'
printf "\t%s\n" $NTP

You have to set IFS to newline first, and then NOT quote the variable, so that the input is split by lines before printf reads it.

It might be more convenient later on if you stored the output in an array instead, rather than a scalar variable.

Code:


mapfile -t NTP < <( rpm -qa | grep ntp )  # mapfile was added in bash 4.0
printf "\t%s\n" "${NTP[@]}"


diamonty 11-25-2011 04:40 PM

Thanks Sycamorex
I'll use tags the next time...

diamonty 11-25-2011 04:43 PM

David the H

The solution: echo "$NTP" | sed 's/^/\t/' is exactly what I need, thanks very much for your help and the alternative solutions,

Regards


All times are GMT -5. The time now is 10:19 AM.