【问题标题】:In Linux: How to repeat multiple lines in a file in the same order?在 Linux 中:如何以相同的顺序重复文件中的多行?
【发布时间】:2017-03-04 08:56:05
【问题描述】:

输入文件包含以下几行:

a
b
c

我希望输出为(n 次):

a
b
c
a
b
c

我试过下面的命令,但它不能保持顺序

while read line; do for i in {1..4}; do echo "$line"; done; done < file

但输出是

a
a
b
b
c
c

【问题讨论】:

  • 简单地追加文件 n 次怎么样,比如循环中的cat file1 &gt;&gt; file2?

标签: linux bash text


【解决方案1】:

将seq 与xargs 一起使用:

seq 2 | xargs -Inone cat file

【讨论】:

  • 尽管seq 并非在所有系统上都可用,但该解决方案有效并解决了问题。否决者可以添加解释吗?来自我的 +1。
【解决方案2】:

另一种解决方案可能是

#multicat count filename(s)
multicat() {
        local count=$1
        shift
        for((i=0;i < $count; i++)) {
                cat "$@"
        }
}

multicat 3 abc          # outputs the "abc" file 3 times

【讨论】:

    【解决方案3】:

    printf 和 brace expansion 可用于将字符串重复 N 次,然后可以将其作为输入传递给 cat,cat 完成连接

    的工作
    $ printf "file %.s" {1..4}
    file file file file $ 
    
    $ cat $(printf "file %.s" {1..4})
    a
    b
    c
    a
    b
    c
    a
    b
    c
    a
    b
    c
    


    使用perl,如果文件足够小,可以完全满足内存需求

    $ perl -0777 -ne 'print $_ x 2' file 
    a
    b
    c
    a
    b
    c
    

    【讨论】:

      【解决方案4】:

      打印file 3次的小解决方案:

      cat $(yes file | head -n 3)
      

      命令替换 $() 扩展为 cat file file file。 这仅适用于没有空格和特殊符号(如*)的文件名。如果需要,可以设置IFS=$'\n'和set -o noglob。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-01-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-01-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多