user7116090
user7116090

Reputation:

Remove Leading Spaces from a variable in Bash

I have a script that exports a XML file to my desktop and then extracts all the data in the "id" tags and exports that to a csv file.

xmlstarlet sel -t -m '//id[1]' -v . -n </users/$USER/Desktop/List.xml > /users/$USER/Desktop/List2.csv

I then use the following command to add commas after each number and store it as a variable.

 devices=$(sed "s/$/,/g" /users/$USER/Desktop/List2.csv)

If I echo that variable I get an output that looks like this:

123,
124,
125,

etc.

What I need help with is removing those spaces so that output will look like 123,124,125 with no leading space. I've tried multiple solutions that I can't get to work. Any help would be amazing!

Upvotes: 0

Views: 800

Answers (2)

picobyte
picobyte

Reputation: 21

For a sed solution, try

sed ':a;N;$!ba;y/\n/,/' /users/$USER/Desktop/List2.csv

or if you want a comma even after the last:

sed ':a;N;$!ba;y/\n/,/;s/$/,/' /users/$USER/Desktop/List2.csv

but then more easy would be

cat /users/$USER/Desktop/List2.csv | tr "\n" ","

Upvotes: 0

Charles Duffy
Charles Duffy

Reputation: 295914

If you don't want newlines, don't tell xmlstarlet to put them there in the first place.

That is, change -n to -o , to put a comma after each value rather than a newline:

{ xmlstarlet sel -t -m '//id[1]' -v . -o ',' && printf '\n'; } \
  <"/users/$USER/Desktop/List.xml" \
  >"/users/$USER/Desktop/List2.csv"

The printf '\n' here puts a final newline at the end of your CSV file after xmlstarlet has finished writing its output.

If you don't want the trailing , this leaves on the output file, the easiest way to be rid of it is to read the result of xmlstarlet into a variable and manipulate it there:

content=$(xmlstarlet sel -t -m '//id[1]' -v . -o ',' <"/users/$USER/Desktop/List.xml")
printf '%s\n' "${content%,}" >"/users/$USER/Desktop/List2.csv"

Upvotes: 4

Related Questions