[英]AWK command to print until end of line
我有一个关于 AWK 命令的快速问题。 我需要命令打印到同一行的行尾,但是当它到达下一行时,我需要它在另一行打印。 以下示例将提供更好的清晰度。
说我有一个文件:
0 1 2 3 This is line one
0 1 2 3 This is line two
0 1 2 3 This is line three
0 1 2 3 This is line four
我已经尝试了以下并得到以下结果
awk '{for(i=5;i<=NF;i++) print $i}' fileName >> resultsExample1
我在 resultsExample1 中得到以下结果
This
is
line
one
This
is
line
two
And so on....
示例 2:
awk 'BEGIN {" "} {for(i=5;i<=NF;i++) printf $1}' fileName >> resultsExample2
对于 resultsExample2 我得到:
This is line one This is line two this is line three This is line four
我也试过:
awk 'BEGIN {" "} {for(i=5;i<=NF;i++) printf $1}' fileName >> resultsExample3
但是结果和上一个一样
最后,我想要以下内容:
This is line one
This is line two
This is line three
This is line four
我很感激任何帮助! 提前致谢 :)
我知道这个问题很老了,但是另一个 awk 示例:
awk '{print substr($0,index($0,$5))}' fileName
它的作用:找到要开始打印的索引($0 中的 $5 索引)并从该索引开始打印 $0 的子字符串。
或 awk
awk '{$1=$2=$3=$4=""; sub(/^ */,"", $0); print }' awkTest2.txt
This is line one
This is line two
This is line three
This is line four
此外,您的解决方案几乎就在那里,您只需要在每个处理行的末尾强制打印 '\\n',即
awk '{for(i=5;i<=NF;i++) {printf $i " "} ; printf "\n"}' awkTest2.txt
This is line one
This is line two
This is line three
This is line four
请注意,您的BEGIN { " " }
不是操作。 并且您应该使用$i
而不是$1
来打印当前迭代值。
IHTH。
编辑; 注意到 sudo_O 反对,我在数据中添加了一个 %s。 这是输出
This is line one
This is line two
This is line three
T%shis is line four
这对您来说可能是个问题,因此在这种情况下,请阅读有关如何将格式字符串传递给 printf 的信息。
使用cut
可能更直接:
$ cut -d' ' -f5- file
This is line one
This is line two
This is line three
This is line four
这表示:在空格分隔的字段上,从第 5 行到行尾打印。
如果您碰巧在字段之间有多个空格,您最初可能想用tr -s' '
挤压它们。
awk '{gsub (/[[:digit:]]/,"");{$1=$1}}1' file
sed
为这个问题提供了最好的解决方案。
公认的基于切割的解决方案存在的问题是,与 awk 不同,它假设字段之间恰好有一个空格。
使用tr -s ' '
将多个相邻空格压缩到一个空格中的通常解决方法也有问题:它会折叠行尾剩余部分中的空格,从而修改它,正如@inopinatus 所评论的那样。
以下基于 sed 的解决方案将实现我们的目标,同时保留该行其余部分的空间:
sed -E 's/^([^ \t]*[ \t]*){4}//' <<'EOF'
0 1 2 3 This is line one
0 1 2 3 This is line two test of extra spaces
0 1 2 3 This is line three
0 1 2 3 This is line four
EOF
结果:
This is line one
This is line two test of extra spaces
This is line three
This is line four
我们模拟了 awk 通过空格序列分隔字段的默认行为。
字段通常由空格序列(空格、制表符和换行符)分隔
– 默认字段拆分(GNU Awk 用户指南)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.