2010-04-20 69 views
1

例如,我需要刪除第25列,並將其替換爲第22列的副本,但不包含嵌入的分隔符。我能想出的最好的是尷尬的看着: 在分隔文件中將一列複製到另一列

 
awk -F, '{ for(x=1;x<25;x++){printf("%s,", $x)};printf("%s,",$22);for(x=26;x<59;x++){printf 
("%s,", $x)};print $59}' 
I would expect something like
 
cut -d, -f1-24,23,26-59 
to work but cut doesn't seem to want to print the same column two times...

Is there a more elegant way to do it using anything typicaly available in a linux shell environment?

+0

這是一種可悲的是切不支持,那肯定是一個非常有用的功能。 – 2010-04-20 16:19:23

+0

'cut'不重新排列列,或者:'echo -e「a \ tb \ tc」| cut -f 3,2,1'結果爲「a [tab] b [tab] c」 – 2010-04-20 17:07:56

回答

4

只要告訴AWK與現場更換田地25 22

awk 'BEGIN{FS=","; OFS=","} {$25=$22; print}' < test.csv 
+1

不需要輸入重定向 - awk將文件名作爲參數。 – Cascabel 2010-04-20 16:33:44

+0

我不知道如何在不列舉列的情況下進行打印。這是很好的知道。 – frankc 2010-04-20 20:37:47

0

It's not elegant, but pastecoreutils一部分,應該是可用的,但它會採取一些臨時文件:

$ cat test.csv 
one,two,three,four,five,six,seven 
1,2,3,4,5,6,7 
$ cut -d, -f1-5 test.csv > start.txt 
$ cut -d, -f3 test.csv> replace.txt 
$ cut -d, -f7 test.csv > end.txt 
$ paste -d, start.txt replace.txt end.txt 
one,two,three,four,five,three,seven 
1,2,3,4,5,3,7 

或者,您可以跳過最後一個臨時文件,並使用標準輸入:

$ cut -d, -f7 test.csv | paste -d, start.txt replace.txt - 
one,two,three,four,five,three,seven 
1,2,3,4,5,3,7 
+0

'cat'的無用用途。 – 2010-04-20 17:04:16

+0

@丹尼斯 - 點,糾正。 – 2010-04-20 17:08:56

0

這可能會實現FO R您:

echo '1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26' | 
sed 's/^\(\([^,]*,\)\{21\}\([^,]*,\)\([^,]*,\)\{2\}\)[^,]*,/\1\3/' 
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,22,26 

或者如果你喜歡:

echo '1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26' | 
sed -r 's/^(([^,]*,){21}([^,]*,)([^,]*,){2})[^,]*,/\1\3/' 
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,22,26 
相關問題