简体   繁体   English

从Bash中的变量中删除前导空格

[英]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. 我有一个脚本,可以将XML文件导出到桌面,然后提取“ id”标签中的所有数据,然后将其导出到csv文件。

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. 我需要帮助的是删除这些空格,以便输出看起来像123,124,125,而没有前导空格。 I've tried multiple solutions that I can't get to work. 我尝试了多种无法使用的解决方案。 Any help would be amazing! 任何帮助都将是惊人的!

If you don't want newlines, don't tell xmlstarlet to put them there in the first place. 如果您不想换行,请不要告诉xmlstarlet首先将它们放在那里。

That is, change -n to -o , to put a comma after each value rather than a newline: 也就是说,将-n更改为-o ,以在每个值后面加上逗号而不是换行符:

{ 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. xmlstarlet完成写入输出后,这里的printf '\\n'将最后的换行符放在CSV文件的末尾。

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: 如果您不希望尾随它,它会留在输出文件上,最简单的摆脱方法是将xmlstarlet的结果读入一个变量并在那里进行操作:

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

For a sed solution, try 对于sed解决方案,请尝试

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" ","

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM