Home > database >  Shell Scripting - how to read text file and create a list from it by add a single digit at the end o
Shell Scripting - how to read text file and create a list from it by add a single digit at the end o

Time:10-08

So let say i have a "fruit.txt" file with a word in each line like

Apple
Banana
Chestnut

how do i read the text file and create a list in the form of

Apple0
Apple1
Apple2
...
Chestnut9

?

CodePudding user response:

Regardless which shell you write your script in, you will need to loop over the names in the file fruit.txt and then loop the number of times you want to append that many digits to each word in the file. Nested loops with the outer looping through the names in fruit.txt and the inner looping once for each digit to append. (to append 0-9 you loop 10 times with the inner loop)

Since you tagged with [shell] you are asking for a POSIX shell compatible solution. That can be something as simple as:

#!/bin/sh

fname="${1:-fruit.txt}"       ## set filename to read (default fruit.txt)
nvers="${2:-10}"              ## take no. of version to create with digits 

## validate file is available and non-empty or exit
[ -s "$fname" ] || {
  printf "error: %s is not found or empty.\n" "$fname" >&2
  exit 1
}

## read each line in fname
while read -r word; do
  n=0                                 ## set counter zero
  while [ "$n" -lt "$nvers" ]; do     ## loop $nvers many times
    printf "%s%d\n" "$word" "$n"      ## write word with digit
    n=$((n 1))                        ## increment counter
  done
done < "$fname"

(if you were using bash, you could use a C-style for((...)) loop for the inner loop)

Example Use/Output

Since there a default values for each fname (fruit.txt) and nver (10), you simply need to run the script if you want the defaults, e.g.

$ sh append_digits.sh
Apple0
Apple1
Apple2
Apple3
...
Chestnut7
Chestnut8
Chestnut9

To create only 4 versions of each fruit you can simply give the necessary arguments, e.g.

$ sh append_digits.sh fruit.txt 4
Apple0
Apple1
Apple2
Apple3
Banana0
Banana1
Banana2
Banana3
Chestnut0
Chestnut1
Chestnut2
Chestnut3

Using awk

The proper tool for the job in shell is awk where you can simply read each line in the file looping however many times needed to append the digits you want, e.g.

$ awk '{ for(i=0; i<10; i  ) print $1 i }' fruit.txt
Apple0
Apple1
Apple2
Apple3
...
Chestnut7
Chestnut8
Chestnut9

If you want to pass-in the number of versions to create you can use the -v option to declare an awk variable on the command line, e.g.

awk -v n=4 '{ for(i=0; i<n; i  ) print $1 i }' fruit.txt

Which would output 0-3 versions of each fruit. Much easier.

  • Related