我有一个包含3列的列表:
2547123456789,5391074043372870,639027123456789
我想像这样修改第二列:
sed 's/\([0-9]\)\([0-9]\)/\2\1/g' so that it becomes:
3519700434738207
我的问题是如何在一行awk / sed中执行此操作,同时保持其他列不变,以便我的最终文件具有:
2547123456789,3519700434738207,639027123456789
由于
答案 0 :(得分:3)
试试这个:
sed 'h;s/.*,\([^,]*\),.*/\1/;s/\(.\)\(.\)/\2\1/g;G;s/\([^\n]*\)\n\([^,]*,\)[^,]*\(.*\)/\2\1\3/' inputfile
说明:
# copy the line to hold space
h;
# capture the second column and retain it in pattern space
s/.*,\([^,]*\),.*/\1/;
# swap each pair of characters
s/\(.\)\(.\)/\2\1/g;
# append the contents of hold space, now pattern space looks like
# new_field_2[newline]field_1,old_field_2,field_3
G;
# capture the fields that we want and arrange them in the proper order
s/\([^\n]*\)\n\([^,]*,\)[^,]*\(.*\)/\2\1\3/
答案 1 :(得分:1)
#!/bin/sh
awk -F, '{
printf("%s,",$1)
len=split($2,a,"")
for(i=1;i<len;i+=2)
printf("%s%s",a[i+1],a[i])
printf(",%s\n",$3)
}' /path/to/input/file
$ cat infile
2547123456789,5391074043372870,639027123456789
1234567890123,1234567890123456,123456789012345
awk -F, '{printf("%s,",$1);len=split($2,a,"");for(i=1;i<len;i+=2)printf("%s%s",a[i+1],a[i]);printf(",%s\n",$3)}' ./infile
2547123456789,3519700434738207,639027123456789
1234567890123,2143658709214365,123456789012345