0

I have tab separated text file, the number of fields is not the same for every record. But I want to replace all tabs with commas after 3rd tab in the file.

Input

100 Apple COOK USA EUROPE CHINA
200 Micro BIIL UK INDIA
300 Saums Chul SK

Required out put:

100 Apple COOK USA,EUROPE,CHINA
200 Micro BIIL UK,INDIA
300 Saums Chul SK
0
4

Try this,

sed -i 's#\t#,#4g' file


100 Apple   COOK    USA,EUROPE,CHINA
200 Micro   BIIL    UK,INDIA
300 Saums   Chul    SK
  • 4g to replace the tab with a comma from 4th occurrence in each line.
4
  • It is not working, getting error sed -i is illegal option.
    – vijay
    Jul 9 '19 at 12:55
  • @chavakumar which distro are u using? is it Mac?
    – Siva
    Jul 9 '19 at 12:56
  • This answer is very specific to GNU sed. If you're on a Mac, install GNU sed with Homebrew: brew.sh Jul 9 '19 at 14:52
  • I had tried to execute this command on AIX server. version is 7.1.0.0
    – vijay
    Jul 9 '19 at 18:02
2

Using awk:

awk  'BEGIN{OFS=IFS="      ";}{for(i=5;i<=NF;i++){$4=$4","$i;} print $1,$2,$3,$4}' file

Output for your case will be:

100 Apple   COOK    USA,EUROPE,CHINA
200 Micro   BIIL    UK,INDIA
300 Saums   Chul    SK

The awk command will read line by line from file. Now it will print first second third word as it is but after fourth word it will concat them with comma.

2
  • Thanks a lot. Command returning expected output. Could you please explain how it is working.
    – vijay
    Jul 11 '19 at 9:59
  • See updated answer.
    – Prvt_Yadav
    Jul 11 '19 at 10:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.