Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
309 views
in Technique[技术] by (71.8m points)

Need to export values stored in 2 different variables to two separate columns in csv file using bash script

My bash script stores data in 2 different variables like -:

Var1="My deployment name is A"
Var2="My deployment url is B"

Note:- Var1 and Var2 contains multiple lines and hence need to export in csv to respective columns i.e. 1st and 2nd column.

I would like to export these 2 values to CSV file so that value of Var1 goes to 1st column and Var2 to 2nd column of same CSV file. like -

enter image description here

Can some one please help me on this ? Thanks in advance.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Two Variables = Two Cells

If the variables never contain special symbols like " or , or linebreaks then it is as simple as

echo "$Var1,$Var2" > file.csv

If there could be a special symbol inside them, you have to quote them, for instance using

printf '"%s","%s"
' "${Var1//"/""}" "${Var2//"/""}"  > file.csv

Two Variables = Two Columns With Multiple Cells (One Cell Per Line)

Without quoting

paste -d, <(echo "$Var1") <(echo "$Var2") > file.csv

With quoting

varToCol() {
  sed 's/"/""/g;s/.*/"&"/' <<< "${!1}"
}
paste -d, <(varToCol Var1) <(varToCol Var2) > file.csv

For a pure bash solution replace the function with the following. Please note: Below bash solution adds an unnecessary empty field at the bottom of the column, if the variable ends with a newline character.

varToCol() {
  local col="${!1//"/""}"
  printf %s\n ""${col//$'
'/$'"
"'}""
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...