Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
308 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 Answer

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//$'
'/$'"
"'}""
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...