4

The following variable include for example this values

echo $SERVERS


server1,server2,server3,server4,server5

and when I want to pipe them on different lines then I do the following

echo $SERVERS | tr ',' '\n'

server1
server2
server3
server4
server5

now I want to add another pipe ( echo $SERVERS | tr ',' '\n' | ..... ) , in order to print the following expected results

1  ………………  server1
2  ………………… server2
3  ………………… server3
4  ………………… server4
5  ………………… server5
6  ………………  server6
7  ………………… server7
8  ………………… server8
9  ………………… server9
10 ………………… server10
11 ………………… server11
12 ………………… server12

Not sure how to do it but maybe with nc command os similar

Any suggestion?

3 Answers 3

8

With awk:

$ servers='server1,server2,server3,server4,server5'

$ awk -v RS=, '{print NR "........" $0}' <<<"$servers"
1........server1
2........server2
3........server3
4........server4
5........server5

or, to output the line numbers with left-padding

awk -v RS=, '{printf "%3d........%s\n",NR,$0}' <<<"$servers"

(choose the field width 3 as appropriate for the size of your server list).

8
  • is it possible to add printf , so it will be alignment when number are bigger then 10 ( I update my question ) Commented Feb 9, 2020 at 13:12
  • @yael like printf "%3d........%s\n",NR,$0you mean? sure Commented Feb 9, 2020 at 13:17
  • yes , Iit will be great if you add this to your answer Commented Feb 9, 2020 at 13:22
  • That will print an extra blank line at the end of the output since <<< ensures the generated string has a terminating newline. Commented Feb 9, 2020 at 13:42
  • 1
    You could be right but I feel like trailing blanks at the end of lines or trailing newlines at the end of output are something that don't get noticed at first and then they often cause some head-scratching down the road when they DO cause a problem and then people "fix" it by tacking on a pipe to some other command to remove them... so best just never to output them in the first place. The printf workaround you suggest has the problkem that it's output isn't a POSIX text file due to no terminating newline so YMMV with what any given tool will do with it (though it'll probably be OK). Commented Feb 9, 2020 at 13:59
3
cat -n <<< ${SERVERS//,/$'\n'} 
     1  server1
     2  server2
     3  server3
     4  server4
     5  server5
3
$ awk -F',' '{for (i=1; i<=NF; i++) printf "%-2d ........ %s\n", i, $i}' <<<"$servers"
1  ........ server1
2  ........ server2
3  ........ server3
4  ........ server4
5  ........ server5

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.