【问题标题】:Use awk to print custom lines使用 awk 打印自定义行
【发布时间】:2015-05-27 11:35:11
【问题描述】:

我有一个这样的文件:

>ref
AAAAAAA
>seq1
BBBBBBB
>seq2
CCCCCCC
>seq3
DDDDDD

我想得到:

>ref
AAAAAAA
>seq1
BBBBBBB
>ref
AAAAAAA
>seq2
CCCCCCC
>ref
AAAAAAA
>seq3
DDDDDD

我正在考虑在 bash 中使用这个命令:

ref=$(head -n 2 file)
awk '/>/{print "'"$ref"'"}1' file

这是我得到的:

awk: non-terminated string >ref... at source line 2
 context is
    />/{print ">ref >>> 
 <<< 

知道发生了什么吗? :) 非常感谢!


编辑:我想将此管道用于所有以不同 ref 开头的文件:ref1 用于 file1ref2 用于 file2,...因此考虑使用 head将每个ref 存储在一个变量中以将其用于每个文件:)

【问题讨论】:

    标签: bash awk head


    【解决方案1】:

    问题

    问题是当ref有值时

    >ref
    AAAAAA
    

    你的 awk 调用

    awk '/>/{print "'"$ref"'"}1' file
    

    结果

    awk '/>/{print ">ref
    AAAAAA"}1' file
    

    shell 扩展后。 awk 不允许字符串文字中的换行符,所以这会爆炸。如果文件的前两行是

    >ref"
    print "AAAAA
    

    它会起作用(除了顶部会有绒毛),但这并不能帮助我们找到一个理智的解决方案。

    awk 中的解决方案

    使用 awk 解决此问题的一种方法是在 awk 本身中组装 ref

    awk 'NR <= 2 { ref = ref $0 ORS; next } />/ { $0 = ref $0 } 1' filename
    

    那是

    NR <= 2 {                # First two lines:
      ref = ref $0 ORS       # build ref string (ORS is "\n" by default)
      next                   # and stop there
    }
    />/ {                    # after that: For lines that contain a >
      $0 = ref $0            # prepend ref
    }
    1                        # then print
    

    sed 中的解决方案

    其实我更喜欢sed这个:

    sed '1h; 2H; 1,2d; />/{ x; p; x; }' filename
    

    即:

    1h                # first line: save to hold buffer
    2H                # second line: append to hold buffer
    1,2d              # first two lines: stop here
    />/ {             # after that: If line contains >
      x               # swap hold buffer, pattern space
      p               # print what used to be in the hold buffer (the first
                      # two lines that we saved above)
      x               # swap back
    }
                      # when we drop off the end, the original line will be
                      # printed.
    

    【讨论】:

    • 非常感谢!我真的很喜欢这些解释! :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-22
    • 2018-07-12
    • 1970-01-01
    相关资源
    最近更新 更多