2

I have a input.txt file with following format:

Name  age  number       address
mark  23   89756342192   chennai
david 40   70214789023   delhi

How do I create a CSV file from a TXT file as per the following example? Thanks.

mark,23,89756342192,chennai
david,40,70214789023,delhi

Below is the script i have written

printrep.sh

#!/bin/sh
Headers=["Name","Age","Phone","Address"];
count=$(wc -l < $name)
i=0;
echo "Headers[0] + ' , ' +Headers[1]+ ' , ' +Headers[2] + ' , ' +Headers[3] + ' , ' +Headers[4]";
while [ $i -lt $count ]
do
        read line | awk FS=' ' OFS="," '{print $0}'
        i=`expr $i + 1`
done

The above code is unable to display the output. And i Can't figure what is wrong. Please help I am a beginner to shell scripting

10
  • 1
    printrep.sh would benefit from being passed through shellcheck.net It's clear that either you've not tried to run it or else you're not telling us the errors you have received. Commented Jul 20, 2022 at 12:12
  • @roaima when i made the block bold the ** came automatically, i didn't realise it.
    – user1998
    Commented Jul 20, 2022 at 12:13
  • @roaima no leading/trailing spaces. I have not copy pasted the code, So didn't include the shebang line. But am using bash shell
    – user1998
    Commented Jul 20, 2022 at 12:16
  • @roaima i have tried running it but no output is displayed and i can't figure out what is wrong it the code. I am a begginer to shell scripting
    – user1998
    Commented Jul 20, 2022 at 12:19
  • 1
    Please don't add extra space. Provide the file in the right format Commented Jul 20, 2022 at 13:16

3 Answers 3

4

bash: the IFS variable is key here. This is bash specific for the use of arrays and read -a

IFS=,
while IFS=$' \t' read -ra fields; do echo "${fields[*]}"; done < input.txt

awk: very terse: $1=$1 rewrites the current line using the output field separator, and 1 to print the line.

awk '{$1=$1}1' OFS=, input.txt

miller: this requires the input file to not have empty lines: convert from "pretty-print" format to csv

mlr --p2c cat input.txt

This also correctly handles commas in the input:

$ cat input.txt
Name  age  number        address
mark  23   89756342192   chennai
david 40   70214789023   delhi
alice 24   42            paris,texas

$ mlr --p2c cat input.txt
Name,age,number,address
mark,23,89756342192,chennai
david,40,70214789023,delhi
alice,24,42,"paris,texas"
1

There are bunch of ways:

cut --output-delimiter="," -c1-6,7-11,12-25,26- < file
tr -s " " "," <file
sed -e "s/  */,/g" <file
1
sed -r -i 's/\s+/,/g' file.txt
output

cat file.txt 
Name,age,number,address
mark,23,89756342192,chennai
david,40,70214789023,delhi
0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .