unix AWK命令打印到行尾

7kqas0il  于 7个月前  发布在  Unix
关注(0)|答案(5)|浏览(89)

我有一个关于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


我在resultsExample 1中得到以下结果

This
is
line
one
This 
is 
line 
two 
And so on....


实施例2:

awk 'BEGIN {" "} {for(i=5;i<=NF;i++) printf $1}' fileName >> resultsExample2


for resultsExample 2我得到:

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


我很感激任何帮助!提前感谢:)

rsl1atfo

rsl1atfo1#

我知道这个问题很古老,但另一个awk例子:

awk '{print substr($0,index($0,$5))}' fileName

字符串
它做什么:找到你想要开始打印的索引(在$0中索引$5),并从该索引开始打印$0的子字符串。
警告:
如注解中所述,如果$5在前面的字段中不是唯一的,则这将失败。

mlmc2os5

mlmc2os52#

使用cut可能更直接:

$ cut -d' ' -f5- file
This is line one
This is line two 
This is line three 
This is line four

字符串
这是说:在空格分隔的字段上,从第5行打印到行尾。
如果你碰巧在字段之间有多个空格,你最初可能想用tr -s' '来压缩它们。

zte4gxcn

zte4gxcn3#

带awk的OR

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来打印当前迭代值。
是的。

Edit;注意到sudo_O的反对意见,我在数据中添加了一个%s。

This is line one
This is line two
This is line three
T%shis is line four


这对您来说可能是个问题,因此在这种情况下,请阅读如何将格式字符串传递给printf。

new9mtju

new9mtju5#

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的默认行为,即用空格序列来分隔字段。
字段通常由空格序列(空格、TAB和换行符)分隔

相关问题