How to write text file data into same cell of exce

2019-07-22 20:17发布

I have a scenario where I want to redirect all the output of a text file into a single cell of excel.

text file data:

"remove dead code" 
"keep cassandra and postgres in OR condition"
"InsertFailCDRList"
"to be updated in error handling US, write TODO here in comments"

I want this data in my one column. For eg.

    C1             C2
    1            TEXT FILE OUTPUT HERE
    2            OTHER TEXT FILE OUTPUT HERE

But problem is text is not coming single cell but it spreads to multiple cells.

Using commands:

#!/bin/bash  -x
output=$(cat commentmessage.txt)
number=1
echo $number,"${output}" > buc_review_comments_data3.csv

Output is like:

        C1             C2
         1            "remove dead code"
        "keep cassandra and postgres in OR coniditon"
        "InsterFailCDRList"

I want all under row 1 column 2. How can we do this using bash? Please help.

Desired Output:

       C1                C2
        1            "remove dead code"
                     "keep cassandra and postgres in OR coniditon"
                      "InsterFailCDRList"

        2             "new data here"
                      "new data"

Format required - this is result wanted

So Basically, I have ID=BUC123

totalcomments=4

Text file - containing multiple comments.

Want these in above format in excel.

标签: excel bash shell
1条回答
不美不萌又怎样
2楼-- · 2019-07-22 20:42

You can use a while loop to iterate over the contents of your input file, and then prefix each line with your number:

#!/bin/bash
infile=commentmessage.txt
outfile=buc_review_comments_data3.csv
number=1

while read line
do
    echo "$number","$line"
done < "$infile" > "$outfile"

Let me add a few hints:

  • Curly braces are mainly useful to separate variable names from other characters that are allowed in variable names inside double quotes, e.g.: "${myvar}otherstuff". But they can also enhance readability of your code. In your example, you could do echo "$number,$line" as well (because , is not allowed in variable names), but echo "${number},${line} would be nice and clear about what your variable names are, while saving the separate quoting.
  • While it is not necessary to quote $number in your example, as a best-practice, you should always double-quote your variable expansions.
  • If you just read from a file, use redirection (<) instead of cat, see Useless Use of cat.
查看更多
登录 后发表回答