加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

bash – 替换文件中的列,但保留空格格式

发布时间:2020-12-16 01:58:26 所属栏目:安全 来源:网络整理
导读:我有一个代码,根据fileB中的数据替换fileA中的第4列,但输出没有保留原始文件的空格.无论如何要做到这一点? tr," " fileB | awk 'NR==FNR{a[$2]=$1;next} {$4=a[$4];print}' - fileA 的fileA xxx xxx xxx Z0002 FILEB 3100,3000 W0002,Z0002 使用上面的代码
我有一个代码,根据fileB中的数据替换fileA中的第4列,但输出没有保留原始文件的空格.无论如何要做到这一点?

tr," " <fileB | awk 'NR==FNR{a[$2]=$1;next} {$4=a[$4];print}' - fileA

的fileA

xxx    xxx   xxx Z0002

FILEB

3100,3000
 W0002,Z0002

使用上面的代码输出:

xxx xxx xxx W0002

预期产量:

xxx    xxx   xxx W0002

解决方法

这应该做:

awk 'FNR==NR {split($0,a,",");b[a[2]]=a[1];next} {n=split($0,d,/[^[:space:]]*/);if(b[$4])$4=b[$4];for(i=1;i<=n;i++) printf("%s%s",d[i],$i);print ""}' fileB fileA

它将空间存储在一个数组中,以便以后可以重用它

例:

cat fileA
xxx    xxx   xxx Z0002   not change this
xxx   xxx  Z0002 zzz
xxx Z000223213 xxx Z0002 xxx xxx xxx Z0002
cat fileB
3100,3000
W0002,Z0002
awk 'FNR==NR {split($0,$i);print ""}' fileB fileA
xxx    xxx   xxx  W0002   not change this
xxx   xxx  Z0002 zzz
xxx Z000223213 xxx  W0002 xxx xxx xxx Z0002

一些更具可读性及其工作原理:

awk '
FNR==NR {                           # For the first file "fileB"
    split($0,")                 # Split it to an array "a" using "," as separator 
    b[a[2]]=a[1]                    # Store the data in array "b" using second column as index
    next                            # Skip to next record
    }
    {                               # Then for the file "fileA"
    n=split($0,/[^[:space:]]*/)   # Split the spaces inn group and store them in array "d"
    if(b[$4])                       # If array "b" as data for field "4"
        $4=b[$4]                    # Change filed "4" to data found in array "b"
    for(i=1;i<=n;i++)               # Loop trough all field in the line
        printf("%s%s",$i)      # print correct separator and data
    print ""                        # Add new line at the end
    }
' fileB fileA                       # Read the files.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读