如何将最后一列移到第n列?

时间:2014-05-27 12:21:52

标签: linux shell awk sed

我需要将文本的最后一列移到第n位,我尝试了很多awk的变种但是不能保持文件的alingment。

以下是我正在处理的文件的副本:

2014-05-27T02:26:46-05:00 nil-severity uuuu vvvvv xxxx yyyy zzzz  
2014-05-27T02:26:22-05:00 nil-severity vvvvv xxxx yyyy zzzz    
2014-05-27T02:25:58-05:00 nil-severity xxxx yyyy zzzz  
2014-05-27T02:25:58-05:00 nil-severity yyyy zzzz  
2014-05-27T02:25:58-05:00 nil-severity vvvvv xxxx yyyy zzzz  

期望的输出:

2014-05-27T02:26:46-05:00 nil-severity zzzz uuuu vvvvv xxxx yyyy   
2014-05-27T02:26:22-05:00 nil-severity zzzz vvvvv xxxx yyyy     
2014-05-27T02:25:58-05:00 nil-severity zzzz xxxx yyyy  
2014-05-27T02:25:58-05:00 nil-severity zzzz yyyy  
2014-05-27T02:25:58-05:00 nil-severity zzzz vvvvv xxxx yyyy  

5 个答案:

答案 0 :(得分:4)

用于将最后一列移动到第三列的简短awk命令:

awk '{$3=$NF OFS $3;$NF=""}1' file

答案 1 :(得分:2)

避免手动弄乱FS,让awk为您完成工作,

awk '{for (i = NF; i >= 3; i--) {$(i+1) = $i}; $3=$NF; NF--}1'

答案 2 :(得分:1)

awk '{s = ""; for (i = 3; i < NF; i++) s = s $i FS; print $1, $2, $NF, s}'

答案 3 :(得分:0)

使用awk

awk '{printf $1" "$2" "$NF" "; for (i=3;i<NF;i++) printf $i" "; printf "\n"}' file

2014-05-27T02:26:46-05:00 nil-severity zzzz uuuu vvvvv xxxx yyyy 
2014-05-27T02:26:22-05:00 nil-severity zzzz vvvvv xxxx yyyy 
2014-05-27T02:25:58-05:00 nil-severity zzzz xxxx yyyy 
2014-05-27T02:25:58-05:00 nil-severity zzzz yyyy 
2014-05-27T02:25:58-05:00 nil-severity zzzz vvvvv xxxx yyyy 

希望这有帮助

答案 4 :(得分:0)

尝试使用此sed命令,

sed -r 's/^(.*severity) (.*) (.*)$/\1 \3 \2/g' file

示例:

$ cat aa

2014-05-27T02:26:46-05:00 nil-severity uuuu vvvvv xxxx yyyy zzzz
2014-05-27T02:26:22-05:00 nil-severity vvvvv xxxx yyyy zzzz
2014-05-27T02:25:58-05:00 nil-severity xxxx yyyy zzzz
2014-05-27T02:25:58-05:00 nil-severity yyyy zzzz
2014-05-27T02:25:58-05:00 nil-severity vvvvv xxxx yyyy zzzz

$ sed -r 's/^(.*severity) (.*) (.*)$/\1 \3 \2/g' aa

2014-05-27T02:26:46-05:00 nil-severity zzzz uuuu vvvvv xxxx yyyy
2014-05-27T02:26:22-05:00 nil-severity zzzz vvvvv xxxx yyyy
2014-05-27T02:25:58-05:00 nil-severity zzzz xxxx yyyy
2014-05-27T02:25:58-05:00 nil-severity zzzz yyyy
2014-05-27T02:25:58-05:00 nil-severity zzzz vvvvv xxxx yyyy

<强>解释

sed -r 's/^(.*severity) (.*) (.*)$/\1 \3 \2/g' file

^(.*severity) - 捕获所有字符到严重程度,然后将其存储到一个组(1)中。

- 匹配紧接着严重一词的空格。

(.*) (.*)$ - 获取severity之后的空格旁边的所有字符,直到最后一个空格并将其存储到组(2)。至少第三组包含直到最后一个空格的所有字符,直到结束。

在替换部分中,我们只是根据所需的输出重新排列捕获的组。