AWK或sed方式粘贴不相邻的行 [英] AWK or sed way to paste non-adjacent lines

查看:65
本文介绍了AWK或sed方式粘贴不相邻的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

$ cat file
aaa bbb ccc
ddd eee
jjj kkk lll
mmm
nnn ooo ppp

以下AWK命令会将'mmm'行粘贴到'ddd eee'行的末尾.有没有更简单的方法可以使用AWK或sed做到这一点?

The following AWK command will paste the 'mmm' line at the end of the 'ddd eee' line. Is there a simpler way to do this using AWK or sed?

$ awk 'FNR==NR {if (NR==4) foo=$0; next} FNR==2 {print $0" "foo; next} FNR==4 {next} 1' file file
aaa bbb ccc
ddd eee mmm
jjj kkk lll
nnn ooo ppp

要澄清一下:我想在此特定文件的第2行的末尾粘贴第4行,在"ddd eee"和"mmm"之间留一个空格.那是任务.有没有比我想出的解决方案更简单的AWK或sed解决方案?

To clarify: I want to paste line 4 at the end of line 2 in this particular file, with a single space between the 'ddd eee' and the 'mmm'. That's the task. Is there an AWK or sed solution that's simpler than the one I came up with?

推荐答案

这可以使用保留空间在 sed 中完成:

This can be done in sed using the hold space:

sed '2{N;h;N;s/\n.*\n/ /;p;g;D;}' file

  • 2 {...} 在第二行中运行随附的命令.
  • N; h; N 将下两行读入模式空间,并保留前两行.
  • s/\ n.* \ n//替换中间行的空格.
  • p; g; D 打印粘贴的行,加载保留空间,然后删除第一行(保留由上一个替代项删除的行).
    • 2{...} Run the enclosed commands on line two.
    • N;h;N Read next two lines into the pattern space, holding the first two.
    • s/\n.*\n/ / Substitute a space for the middle line.
    • p;g;D Print the pasted lines, load the hold space, and delete the first line (leaving the one that was removed by the previous substitute).
    • 或使用捕获( \(... \))&反向引用( \ 1 \ 2 等):

      or using captures (\(...\)) & back-references (\1, \2, etc.):

      sed '2{N;N;s/\(\n.*\)\n\(.*\)/ \2\1/;}' file
      

      • 2 {...} 在第二行中运行随附的命令.
      • N; N 将下两行读入模式空间.
      • s/\(\ n.* \)\ n \(.* \)/\ 2 \ 1/交换第三和第四行,合并第一和第三行.
        • \(\ n.* \)捕获第三行,包括前导换行符.
        • \ n \(.* \)捕获第四行,不包括开头的换行符.
        • /\ 2 \ 1/用空格替换匹配的部分(第三和第四行),然后是第二个,然后是第一个捕获组.
          • 2{...} Run the enclosed commands on line two.
          • N;N Read next two lines into the pattern space.
          • s/\(\n.*\)\n\(.*\)/ \2\1/ Swap the third and fourth line, joining the first and third lines.
            • \(\n.*\) Capture the third line, including the leading newline.
            • \n\(.*\) Capture the fourth line, excluding the leading newline.
            • / \2\1/ Replace the matched portion (the third & fourth lines) with a space, followed by the second, and then the first capture groups.
            • 这篇关于AWK或sed方式粘贴不相邻的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆