【问题标题】:Create files from text list using command line?使用命令行从文本列表创建文件?
【发布时间】:2013-04-28 03:24:57
【问题描述】:

我知道通常你可以使用touch filename 通过命令行创建新文件。但是,在文本文件中,我有一个大约 500 个城市和州的列表,每个都在一个新行上。我需要使用命令行为每个城市/州创建一个新的文本文件。例如,Texas.txt、New York.txt、California.txt

包含列表的文件的名称是 newcities.txt - 这可以在命令行中还是通过 Perl 完成?

【问题讨论】:

    标签: perl shell command-line command


    【解决方案1】:

    来个简单的:

    cat fileName | xargs touch
    

    【讨论】:

    • 更好:xargs touch < fileName
    • 更好:xargs -a filename touch
    • 在原始问题的示例中,“New York”将生成 2 个文件:“New”和“York”。
    【解决方案2】:
    perl -lnwe 'open my $fh,">", "$_.txt" or die "$_: $!";' cities.txt
    

    使用-l 选项自动选择输入。 open 会创建一个新的空文件,并且文件句柄会在超出范围时自动关闭。

    【讨论】:

    • 与大多数其他答案不同,这不会立即产生 sh*t 因为简​​单的空格。不过,添加 s/[\/\&\|;]+/-/g 之类的内容会更好,并且可能会扩展得更全面。
    【解决方案3】:

    这是perl 中的单线,假设每个城市都在新线上

    perl -ne 'chomp; `touch $_`;' newcities.txt
    

    这是脚本版本:

    #!/usr/bin/perl
    
    use warnings;
    use strict;
    
    open my $fh, "<", "./newcities.txt"
      or die "Cannot open file: $!";
    
    while( my $line = <$fh> ){
        chomp $line;
        system("touch $line");
    }
    close $fh;
    

    【讨论】:

    • 文件名前不需要./
    • gaah,你让 shell 用名字做可怕的事情。使用这个:perl -lne 'system touch =&gt; $_' newcities.txt
    • @JulianFondren 你在说什么?不清楚你的改进是什么? -l auto chomps 的事实?为什么你想要一个“胖逗号”,这里有什么特殊用途吗?如果没有,它看起来不合适。例如,您不会有这样的列表:my @l = ('a' =&gt; 'b' =&gt; 'c');。我的意思是你可以,但你不应该。
    • $line = 'haha; rm -rf /'; system("touch $line");
    【解决方案4】:

    你可以直接在shell中做这个,不需要perl

    cat myfile | while read f; do echo "Creating file $f"; touch "$f"; done
    

    【讨论】:

    • 对于您的情况,Youns 解决方案会更短。我更喜欢这个,因为您可以根据需要在一行中包含许多复杂的命令,由';'分隔,即使使用 if 等..
    猜你喜欢
    • 2016-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-29
    • 2013-07-27
    • 1970-01-01
    • 2016-07-05
    • 2022-05-31
    相关资源
    最近更新 更多