Multline output variable in bash for csv file

lolaferrari
lolaferrari used Ask the Experts™
on
Hello,

I have a bash script that I want to output the variables into a .csv file.  Most of the variable I can have the variable output on one line but I'm having a problme with variables that are multiline. The two variables are passed the process id of a process and the process listing contains new line characters. I thought if I stripped out the newline characters that you could assign it to the variable but it complains "No such file or directory in the variable substition".  The other variable is just netstat -an | grep <port>.  I don't know how to use arrays in bash but ideally i'd like to be able to keep the newlines in the csv file, if it's possible, since i'm sticking with comma as the separator. Any help would be really appreciated. Hitting my head off the wall!

VAR1="$(ps -ef | grep 27656 | tr '\n' ' ' | sed -e '/s   */g')"
(printf '%s\n' $VAR1)
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
nociSoftware Engineer
Distinguished Expert 2018

Commented:
"No such file or directory" probably means there is a space after the VAR1= assignment... (Then it can find the program after the assignment VAR1="" ).
and you may want to reconsidder  using (printf....) as that would chop the line into separate words.

$ VAR1= "asdfasdf"
bash: asdfasdf: command not found
$ VAR1="asdf"
$ 

Open in new window

Author

Commented:
Thanks noci. I double checked  the assignment to the var and there wasn't a space but I changed a few things and it's working now. Instead of using var="$( )" notation I've used `` notation but I don't think that should really matter and I used echo -e (thanks for the tip about printf)  and I removed the trailing space characters which I think was the problem.

I have another question though. How can you use sed to remove mutiple space charaters. I'd like to remove all the extra spaces to end up with just single spaces.
Hi lolaferrari,

> "How can you use sed to remove mutiple space charaters. I'd like to remove all the extra spaces to end up with just single spaces."
    sed 's/  */ /g' file
Note the 2 spaces before the '*'.
This means replace each occurrence of 1 space followed by 0 or more spaces with 1 space.

You could alternatively do this:
    sed 's/   */ /g' file
Note the 3 spaces before the '*'.
This means replace each occurrence of 2 spaces followed by 0 or more spaces with 1 space.  This might be slightly more efficient because it doesn't bother replacing a 1 space with 1 space.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial