【问题标题】:Modify column 2 only using awk and sed仅使用 awk 和 sed 修改第 2 列
【发布时间】:2014-08-24 11:46:40
【问题描述】:

我有一个包含 3 列的列表:

2547123456789,5391074043372870,639027123456789

我想像这样修改第二列:

sed 's/\([0-9]\)\([0-9]\)/\2\1/g' so that it becomes:

3519700434738207

我的问题是如何在一行 awk/sed 中执行此操作,同时保持其他列不变,以便我的最终文件具有:

2547123456789,3519700434738207,639027123456789

谢谢

【问题讨论】:

  • 您接受的答案与您要求的结果不同。它只翻转第二个字段的前 2 个字符。如果这确实是您想要的,请更新您的问题以反映这一点。谢谢
  • 我误读了这个问题,并认为g 标志是为了拿起第二列。如果 OP 可以确认他想要什么,我将删除我的答案...

标签: awk sed


【解决方案1】:

试试这个:

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,暂时我认为使用 sed 单线是不可能的;)
  • 工作就像一个魅力:-) 谢谢
【解决方案2】:
#!/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

【讨论】:

    猜你喜欢
    • 2011-01-10
    • 2015-03-19
    • 2021-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多