0

I have a file

cat test.txt

name: amit 
phone: 0000000000

I am trying to display like

name,phone
amit, 000000000

I try

cat test.txt | awk -F":" '{print $1}' | sed -n 's/,$//p'
and
cat test.txt | awk -F":" '{print $1}' | tr  '\n' ,

then save 1st string in CSV and then another by >>

when I use

cat test.txt | awk -F":" '{print $1}' 

it shows

name
phone

my sed or tr is not wokring.. where I am doing wrong...

Inian
  • 80,270
  • 14
  • 142
  • 161
Amit
  • 57
  • 5

1 Answers1

1

You can use

awk -F\: '
{ 
    for (i=1; i<=NF; i++)  {
        gsub(/^[[:blank:]]+|[[:blank:]]+$/, "", $i)
        a[NR,i] = $i
    }
}
NF>p { p = NF }
END {    
    for(j=1; j<=p; j++) {
        str=a[1,j]
        for(i=2; i<=NR; i++){
            str=str","a[i,j];
        }
        print str
    }
}' file
## => name,phone
##    amit,0000000000

See the online demo.

This is based on An efficient way to transpose a file in Bash with few changes:

  • The field separator is set to a colon
  • The leading and trailing whitespaces in a field are removed with the gsub(/^[[:blank:]]+|[[:blank:]]+$/, "", $i) line.
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563