Change delimiter is not working using awk

I have file 2.txt and I want to change the delimiter form , to :
Not sure what is the problem with below command

cat 2.txt
1,a
2,b
3,d
awk 'BEGIN {FS=",";OFS=":";} {print $0}' 2.txt

Hello vamsi.valiveti,

Could you please try following and let me know if this helps you.

awk -F, '{$1=$1} 1' OFS=":"   Input_file

Output will be as follows:

1:a
2:b
3:d

Thanks,
R. Singh

There is no change in output.I did not get expected output

It worked for me, can you check if by any chance your Input_file is having carriage characters in your Input_file? Do this cat -v Input_file if you see carriage characters then do a tr -d '\r' < Input_file > temp_file && mv temp_file Input_file then.

Let me know how it goes then.

Thanks,
R. Singh

Thanks for quick reply.I can get the solution using sed command but just want to know what is the problem with my command posted in question and why it is not working?

If you wouldn't give us proper information how we could let you know? Without seeing your system. So did you try my previous post's commands?

Please do let us know on same.

Thanks,
R. Singh

I tried cat -v 2.txt but there is no '\r'

What operating system are you using?

awk -F, '{$1=$1}1' OFS=: 2.txt

with no space at all in {$1=$1}1

1:a
2:b
3:d

It is working, but mayhap not the way you want it to work. You print the entire line unaltered. And, why should awk modify the line if not triggered to do so? That's what RavinderSingh13 did. man awk :

And this does work, at least for me and obviously for him, spaces in there ad libitum.

I am using AIX

With the awk that is shipped with AIX, there is no reason why the code suggested by RavinderSingh13:

awk -F, '{$1=$1} 1' OFS=":" 2.txt

and the equivalent code suggested byabdulbadii:

awk -F, '{$1=$1}1' OFS=: 2.txt

should not produce the output you say you want as long as a text file named 2.txt contains the sample text you showed us in post #1 in this thread.

Note that I'm only talking about the output produced by these scripts on standard output; I'm not saying that either of these scripts would change the contents of 2.txt (since neither of them would make any change to the input file).

As noted by RudiC in post #10 in this thread, the awk script you included in post #1 is fundamentally different from the code suggested by RavinderSingh13 and by abdulbadii. The code you included should just copy the contents of the named input file(s) to standard output without making any changes (for the reasons RudiC mentioned in his post).

1 Like