1

We have the following file ( it is example )

more machines.txt


Node23
Node34
Node12
Node95
Node23

We want to insert the list of all node to variable and join each node with “,” separator

Example of expected results ( without empty space/s )

Node23,Node34,Node12,Node95,Node23

We try this

LIST=` sed -e 's/\s\+/,/g'  machines.txt ` 

But we this approach not join the separator between machines , and we get

echo $LIST

Node23 Node34 Node12 Node95 Node23

what is the right approach to get the csv list in variable ( this syntax should be in bash script )

3

With paste:

list=$(paste -sd, < machines.txt)
1

The sed command evaluates line-by-line by default. As a result, your command is not replacing the newline. You can confirm this by running:

echo "$LIST"

which would show you that you actually did not do any operation on the original file contents.

Since you are only replacing one character, I would recommend the tr tool as an alternative to sed. The resulting command would look something like this:

LIST=$(tr '\n' ',' < machines.txt) 

Basically the line means that we want to replace newlines \n with a comma ,

If there's a trailing comma, you can also add in a sed command to remove the final comma.

LIST=$(tr '\n' ',' < machines.txt | sed 's/,$//')
  • one problem in your approach that we get also separator in the end , example - Node23,Node34,Node12,Node95,Node23, while we should get - Node23,Node34,Node12,Node95,Node23 – yael Aug 27 at 17:04
  • That means you have a \n at the end of your file. You can remove it via a sed or some other tool. I'll modify my answer with a possible solution – Jason K Lai Aug 27 at 17:10
0

My approach:

$ LIST=$(echo $(<machines.txt) | sed 's/ /,/g')
$ echo "$LIST"
$ Node23,Node34,Node12,Node95,Node23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.