Aires69
Aires69

Reputation: 87

how to insert a delimiter every nth column using shell

I've data as follows

11111 22222 33333 44444                       55555           66666

I would like the output data as follows

11111,22222,3333,4444                       ,55555           ,66666

I tried using the tr command by converting the space with commas but get all commas after the 4444 OR 55555. Note: there is a lot of spaces between 4444 and 5555. Is it possible to fill the space at the 6th, 12th, 17th, 46th,etc column with a comma ?

Upvotes: 0

Views: 165

Answers (2)

RavinderSingh13
RavinderSingh13

Reputation: 133780

If your actual Input_file is same as shown sample then following may help you too in same.

awk '{gsub(/ [0-9]+/,",&");gsub(/, /,",")} 1'   Input_file

Output will be as follows.

11111,22222,33333,44444                      ,55555          ,66666

Explanation of above command:

awk '{
gsub(/ [0-9]+/,",&"); ##gsub is awk utility to substitute things, so its format is gsub(regex_for_strings_to_be_replaced,with_whom_it_should_be_replaced,variable/line). So here I am substituting globally space then all digits(continuous ones) with a comma and (matched regex itself, which is space then all digits(continuous ones)).
gsub(/, /,",")        ##Using gsub again here to replace comma then space(, ) with only comma(,), to get the output into same shape in which OP has asked, it will remove space between command and digits which was created in above command.
}
1                     ##awk works on method of condition then action, so here I am making condition as TRUE by mentioning 1 and not mentioning any action so be default print action will happen, print of current line.
' Input_file          ##Mentioning Input_file name here.

Upvotes: 0

guido
guido

Reputation: 19224

Wouldn't this just do what you are looking for? (guessing the missing 4 in your desired output is a typo)

sed -E 's/ ([0-9])/,\1/g' data

(use -r instead of -E if you are on a mac).

Upvotes: 4

Related Questions