удар выполняет команду для X аргументов за один раз

Я собирался продлить свой оригинальный код, но он добирается до точки, где гораздо проще просто переосмыслить все в Perl напрямую:

#!/usr/bin/env perl

## This is the path to the target  directories
my $path="/Users/Masi/Dropbox/";

## The target directories
my @directories=("Cardiology","Rheumatology","Surgery");

## Iterate over the directories
foreach my $dir (@directories) {
    my $dd=0;
    ## Read the current directory
    opendir (my $DIR, "$path/$dir");
    ## Find all files in this directory
    while (my $file = readdir($DIR)) {
        ## Reset the counter
        my $c=0;
        ## Skip any files that aren't .tex
        next unless $file =~ /\.tex$/;

        ## Open the file
        open(my $fh,"$path/$dir/$file");

        while (<$fh>) {
            ## Get the subsection. $_ is the current line.
            $sub="$_" and $n=0 if /\\subsection{/;
            ## If this line is a question
            if (/\\begin{question}/) {
                ## If this counter is 0, this is the first file
                ## of this directory, so print the section
                ## Print the section name
                if ($dd==0) {
                    print "\\section{$dir}\n\n";
                    $dd++;
                } 
                ## If this counter is 0, this is the first question
                ## of this subsection, so print the subsection line
                print "$sub\n" if $n==0;

                $n++;
                ## Increment the counter, we want these lines
                $c++;
                ## And print
                print;
            }
            else {
                ## Print lines if the counter is 1
                print if $c==1;
                ## reset the counter to 0
                print "\n" and $c=0 if /\\end{question}/;
            }
        }
        print "\n";
    }

}

Обратите внимание, что это игнорирует подкупки, но это было бы легко изменять его, чтобы включить их.

0
13.04.2015, 18:11
2 ответа

Полагаю, вы не описываете свой реальный сценарий: вы хотите не только скопировать сотни тысяч файлов, но и поспать сотни тысяч секунд... wtf?!?

В любом случае:

while IFS= read -r file1
      IFS= read -r file2
do
    cp "$file1" "${file1##*/}-backup"
    cp "$file2" "${file2##*/}-backup"
    sleep 1
done < inputFile
3
28.01.2020, 02:20

Простите : Я не заметил "txt-файл" с "сотнями тысяч строк". Это просто наивное решение...

for a in test*; do ls -l $a; if [[ $((i++ % 2)) != 0 ]]; then sleep 1; fi; done

Update: Объяснение и (частично обновление до txt файла с именами файлов).

... переформатирование:

for a in `cat file.txt`
do 
   cp "$a" "$a-backup"              ## REPLACE THIS LINE 
   if [[ $((i++ % 2)) != 0 ]] then
       sleep 1
   fi
done
  • этот один лайнер означает; для файла in files обрабатывать файл $a и спать, если это четная строка.

Для того, чтобы посмотреть, четная ли строка, мы считаем ее (i++) и видим, что i % 2 равно 0

  • в bash $(( .... exp )) вычисляет ...exp как численное выражение
  • таким образом $((i++ % 2)) != 0 будет истинно даже для итераций (и в этом случае в случае если мы спим 1)
  • в bash [[ ...exp ]] вычисляем ...exp как булевое выражение

Примечание: это решение работало с файлом file.txt, содержащим 100_000 файлов, но для очень большого файла оно не сработает. txt

1
28.01.2020, 02:20

Теги

Похожие вопросы