Home > OS >  Creating files in succession
Creating files in succession

Time:12-02

How would one go about creating a script for creating 25 empty files in succession? (I.e 1-25, 26-51, 52-77)

I can create files 1-25 but I’m having trouble figuring out how to create a script that continues that process from where it left off, every time I run the script.

CodePudding user response:

#!/bin/bash

higher=$( find files -type f -exec basename {} \; | sort -n | tail -1 )

if [[ "$higher" == "" ]]
then
    start=1
    end=25
else
    (( start = higher   1 ))
    (( end = start   25 ))
fi

echo "$start --> $end"

for i in $(seq $start 1 $end)
do
    touch files/"$i"
done
  • I put my files in a directory called "files".
  • hence the find on directory "files".
  • for each file found, I run a basename on it. That will return only integer values, since the files all have a number filename.
  • sort -n puts them in order.
  • tail -1 extracts the highest number.
  • if there are no files, higher will be empty, so the indexes will be 1 and 25.
  • otherwise, they will be higher 1, and higher 26.
  • I used seq for the for loop to avoid problems with variables inside a range definition (you did {1..25})

CodePudding user response:

#! /usr/bin/env bash

declare -r base="${1:-base-%d.txt}"
declare -r lot="${2:-25}"
declare -i idx=1
declare -i n=0

printf -v filename "${base}" ${idx}
while [[ -e "${filename}" ]]; do
    idx =1
    printf -v filename "${base}" "${idx}"
done
while [[ $n -lt $lot ]]; do
    printf -v filename "${base}" ${idx}
    if [[ ! -e "${filename}" ]]; then
        > "$filename"
        n =1
    fi
    idx =1
done

This script accepts two optional parameters.

  1. The first is the basename of your future files with a %d token automatically replaced by the file number. Default value is base-%d.txt;
  2. The number of file to create. Default value is 25.

How script works:

  1. Variable declarations
    • base: file basename (constant)
    • lot: number of file to create (constant)
    • idx: search index
    • n: counter for new files
  2. Search files already created from 1
    • The loop stop at first hole in the numbering
  3. Loop to create empty files
    • The condition in the loop allows to fill in the numbering holes
    • > filename create an empty file
  • Related