Search code examples
stringawkconcatenation

how to proper do a string concatenation in awk


I'm trying to concatenate strings from a .csv file. A simple example data file is:

$ cat a
100, 200, 300
400, 500, 600

And the first approach results in nothing.

$ awk 'BEGIN{FS=",";OFS="-"}{gsub(/ /, "");a=$1$2$3; print $a}' a

In the second approach I also did not get the expected result.

$ awk 'BEGIN{FS=",";OFS="-"}{gsub(/ /, "");a="$1$2$3"; print $a}' a
100,200,300
400,500,600

Expected result would be

100200300
400500600

If the `.csv' file has strings instead of numbers, I still don't get the expected result. Some commas (,) are inserted in the middle, even though I've set the output field separator as dash (-).

$ cat b
AAA, BBB, CCC
DDD, EEE, FFF

$ awk 'BEGIN{FS=",";OFS="-"}{gsub(/ /, "");a=$1$2$3; print $a}' b
AAA,BBB,CCC
DDD,EEE,FFF

In this case, the expected result was

AAABBBCCC
DDDEEEFFF

Solution

  • Try this:

    awk -F', *' -v OFS= '{$1=$1}1' a
    100200300
    400500600
    
    awk -F', *' -v OFS= '{$1=$1}1' b
    AAABBBCCC
    DDDEEEFFF
    

    Set Field Separator to comma and zero or more spaces and Output Fields Separator to nothing, then recreate the fields and print them.

    Or just remove comma space

    awk '{gsub(/, */,"")}1' a
    sed 's/, *//g' a