我需要将文本的最后一列移到第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
答案 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)。至少第三组包含直到最后一个空格的所有字符,直到结束。
在替换部分中,我们只是根据所需的输出重新排列捕获的组。