2021年4月1日星期四

How to write shell script to create txt file with specified file size & repeated strings?

I'm trying to write a shell script to create a textfile that

  1. gets a specified file size (in bytes) & string as input
  2. repeats the string until it fills the file size (WITHOUT NEW LINE)
  3. and adds a marker number when it reaches 1MB, 2MB, etc... (1 for 1MB mark, 2 for 2MB mark)

This is what I tried to write

  #!/bin/bash    # input filesize in bytes  echo -n "input filesize in bytes: "  read fsz    # input string to repeat  echo -n "input string to repeat: "  read str    echo "creating txt file of $fsz bytes, repeating string '$str'..."    # filesize in megabytes (int value)  let "mb = fsz / 1000000"  echo $mb    # when file size is over 1MB  if [ $mb -gt 0 ]  then     for i in {1..$mb};     do echo "$str" | head -c 1000000 >> testfile.txt;     $i >> testfile.txt;     done       let "nb = fsz - mb * 1000000"     echo "$str" | head -c $nb >> testfile.txt  else # if file size is in bytes     echo -e "else\n"     echo "$str" | head -c $fsz >> testfile.txt  fi  

But right now, the resulting testfile.txt only has the string repeated once.
Could anyone please help me to fix this problem?

Thanks!

https://stackoverflow.com/questions/66913164/how-to-write-shell-script-to-create-txt-file-with-specified-file-size-repeated April 02, 2021 at 08:41AM

没有评论:

发表评论