我有一个关于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
Run Code Online (Sandbox Code Playgroud)
我尝试了以下内容并获得了以下结果
awk '{for(i=5;i<=NF;i++) print $i}' fileName >> resultsExample1
Run Code Online (Sandbox Code Playgroud)
我在resultsExample1中得到以下内容
This
is
line
one
This
is
line
two
And so on....
Run Code Online (Sandbox Code Playgroud)
例2:
awk 'BEGIN {" "} {for(i=5;i<=NF;i++) printf $1}' fileName >> resultsExample2
Run Code Online (Sandbox Code Playgroud)
for resultsExample2我得到:
This is line one This is line two this is line three This is line four
Run Code Online (Sandbox Code Playgroud)
我也尝试过:
awk 'BEGIN {" "} {for(i=5;i<=NF;i++) printf $1}' fileName >> resultsExample3
Run Code Online (Sandbox Code Playgroud)
但结果与前一个相同
最后我想要以下内容:
This is line one
This is line two
This is line three
This is line four
Run Code Online (Sandbox Code Playgroud)
我很感激任何帮助!提前致谢 :)
Dan*_*i_l 11
我知道这个问题很老,但是另一个例子是:
awk '{print substr($0,index($0,$5))}' fileName
Run Code Online (Sandbox Code Playgroud)
它的作用:找到你想要开始打印的索引($ 0的索引为$ 0)并从该索引开始打印$ 0的子字符串.
它可能更直接使用cut:
$ cut -d' ' -f5- file
This is line one
This is line two
This is line three
This is line four
Run Code Online (Sandbox Code Playgroud)
这表示:在空格分隔的字段中,从第5行打印到行尾.
如果您在字段之间碰巧有多个空格,您可能最初想要用它们来挤压它们tr -s' '.
或者与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
Run Code Online (Sandbox Code Playgroud)
此外,您的解决方案几乎就在那里,您只需要强制在每个已处理的行的末尾打印'\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
Run Code Online (Sandbox Code Playgroud)
请注意,你BEGIN { " " }是一个没有操作.您应该使用$i而不是$1打印当前的迭代值.
IHTH.
编辑 ; 注意到sudo_O异议,我在数据中添加了%s.这是输出
This is line one
This is line two
This is line three
T%shis is line four
Run Code Online (Sandbox Code Playgroud)
这对您来说可能是个问题,所以在这种情况下会读到如何将格式字符串传递给printf.