简体   繁体   English

使用sed linux交换列

[英]Swap columns using sed linux

My task is to swap second and fourth column in a file using sed : 我的任务是使用sed交换文件中的第二列和第四列:

Filesystem  Size    Used   Avail   Use% Mounted on
rootfs         583G  380G   203G  66%   /
devtmpfs    1.9G   252K   1.9G   1%     /dev
tmpfs         2.0G    2.5M   1.9G   1%     /dev/shm
/dev/sda1  583G   380G  203G  66%   /

my sed script looks like this: 我的sed脚本如下所示:

#!/bin/sed -f
s/\(.*\)\s\+\(.*\)\s\+\(.*\)\s\+\(.*\)\s\+\(.*\)\s\+\(.*\)/\1 \3 \4 \2 \5 \6/g

This does not work and I cannot figure out why. 这行不通,我不知道为什么。 Can anyone please help me? 谁能帮帮我吗? Thank you! 谢谢!

$ sed -E 's/^(\S+\s+)(\S+\s+)(\S+\s+)(\S+\s+)/\1\4\3\2/' ip.txt 
Filesystem  Avail   Used   Size    Use% Mounted on
rootfs         203G  380G   583G  66%   /
devtmpfs    1.9G   252K   1.9G   1%     /dev
tmpfs         1.9G   2.5M   2.0G    1%     /dev/shm
/dev/sda1  203G  380G  583G   66%   /
  • -E use ERE, some sed versions need -r option instead -E使用ERE,某些sed版本需要-r选项
  • ^ start of line anchor ^行锚的起点
  • (\\S+\\s+) defines one column - non-whitespace characters followed by whitespace characters (\\S+\\s+)定义一列-非空白字符,后跟空白字符
    • use it four times to get first four columns 使用它四次以获得前四列
    • then in replacement section, re-arrange in whatever order is required 然后在替换部分中,按照需要的顺序重新排列

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM