2017-10-11 42 views
0

我已經數據如下如何使用殼

11111 22222 33333 44444      55555   66666 

我想的輸出數據通過轉換如下

11111,22222,3333,4444      ,55555   ,66666 

我使用tr命令試圖插入一個分隔符每隔第n列請在4444或55555之後使用逗號。注意:4444和5555之間有很多空格。是否可以用逗號填充第6,12,127,46等列的空格?

+0

只是想大聲這裏,但嘗試用逗號替換空格然後更換後',,'用''(空間) – Dominik

+3

你真的想要一個少' 3'和一個少於'4'的輸出? – jas

+0

感謝您的快速回復。我能解決這個問題。因爲我不得不插入逗號的字段是常量,所以我使用了多個sed命令。所以對於上面的例子,cmd是 – Aires69

回答

0

如果您的實際Input_file與顯示的樣本相同,那麼以下內容可能也會對您有所幫助。

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

輸出如下。

11111,22222,33333,44444      ,55555   ,66666 

說明上面的命令:

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. 
4

難道這只是做你正在尋找什麼? (猜測中所需輸出的失蹤4人是一個錯字)

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

(使用-r而不是-E,如果你是在Mac)。

+0

實際上,macOS的' sed'基於他們從FreeBSD抓取的舊版本,它支持'-E'而不是'-r'。 FreeBSD(和其他BSD)多年來一直支持這兩種選擇。 '-E'旨在等同於grep的'-E'選項(對於「擴展」RE)。我不確定GNU人們在ERE中使用'-r'的想法。 – ghoti