Monday, April 29, 2024
0
rated 0 times [  0] [ 0]  / answers: 1 / hits: 581  / 1 Year ago, sun, december 11, 2022, 1:19:31

I need to generate 100 .txt files with a random number inside each one of them. Then I need to rename the files so that the file names are named from 1.txt to 100.txt in ascending order based on the value that is stored inside each file. The file named 1.txt should have the smallest number stored in it and the file named 100.txt shouild have the largest number stored in it


I tried this code:


#!/bin/bash
for i in $(seq 1 100)
do
echo $RANDOM > ${i}.txt
done
cat *.txt | sort

More From » command-line

 Answers
7

Make a new directory and name the directory whatever name you choose. Change directories with cd to the new directory that you made, so that all of the files that are created by the shell script will be created inside the new directory and only these newly created files will be renamed. Then run the following shell script.


#!/bin/bash
for i in $(seq 1 100)
do
echo $RANDOM > ${i}.txt # Put a random number inside each file.
mv ${i}.txt $(head -1 ${i}.txt).txt # Rename the files.
done
ls *.txt | sort -n # Sort the files in ascending order.

Your question is ambiguous because I could also rename the files in ascending order with new names that range from 1.txt to 100.txt.
If that's how your want the files to be renamed use this shell script instead.


#!/bin/bash
for i in $(seq 1 100)
do
echo $RANDOM > ${i}.txt # put a random number inside each file
mv ${i}.txt $(head -1 ${i}.txt).txt # rename files
done
# ls *.txt | sort -n # I commented out this line and added a new line after it.
i=1; for filename in `ls *.txt | sort -n`; do mv "$filename" "$((i++)).txt"; done

[#939] Monday, December 12, 2022, 1 Year  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
afisird

Total Points: 193
Total Questions: 112
Total Answers: 111

Location: Angola
Member since Mon, Jul 12, 2021
3 Years ago
afisird questions
Wed, Jul 27, 22, 03:53, 2 Years ago
Sun, Mar 12, 23, 18:05, 1 Year ago
Sun, May 1, 22, 18:56, 2 Years ago
;