1

I am trying to get the line contents of file (./answer/answerOnly.txt) to separate files.

Given -> answerOnly.txt:

Ans1
Ans2
Ans3
Ans4

expected output -> files to be created

~/Desktop/miniPro$ ls distributedAnswers/
1.txt
2.txt
3.txt
4.txt

and 1.txt contains:

~/Desktop/miniPro$ cat distributedAnswers/1.txt
Ans1

I have tried ->

for (( i=0;i<count;i++ ))
do
 echo -n `awk 'NR==$i' answer/answerOnly.txt  &> ./distributedAnswers/$i.txt`
done

output : Empty files are getting created

observation : "awk 'NR==$i'" will only accept numbers. Need a way in which 'NR== ?' accepts variable value.

Thanks and your help is appreciated.

  • Did you consider coding such a script in [Python](http://python.org/), or [Ocaml](http://ocaml.org/), or [GNU guile](https://www.gnu.org/software/guile/) or code a simple C program for it? – Basile Starynkevitch Mar 16 '21 at 07:19

2 Answers2

5

Why not use split?

For example:

split -d -l 1 answersOnly.txt  answer_ --additional-suffix=.txt --suffix-length=1 --numeric-suffixes=1

How it works:

  • -d use numeric values
  • -l split by number of lines, here 1
  • answerOnly is your input file
  • answer is your output file
  • --additional-suffix=.txt appends answer with .txt
  • --suffix-length add a suffix of length N
  • --numeric-suffixes same as -d, but allow setting the start value

Or... use bash.

Here's how:

readarray -t LINES < "$1"
COUNT=${#LINES[@]}
for I in "${!LINES[@]}"; do
    INDEX=$(( (I * 12 - 1) / COUNT + 1 ))
    echo "${LINES[I]}" >> "$((I + 1)).txt"
done

Where "$1" is your source file.

baduker
  • 19,152
  • 9
  • 33
  • 56
3

i'm assuming that in the filename ${i}.txt, i is the line number

so would this help?

#set a line counter variable i outside the block
i=0

# start a while loop that reads the file line-by-line
while read line; do

    #increment the counter by 1 for each line read
    i=$(($i+1)) 
    # write to file
    echo "$line" > ${i}.txt

done < answerOnly.txt
# passing the file as input using < (input redirection)
# you could also use `cat answersOnly | while ...etc` but this is cleaner
kevinnls
  • 728
  • 4
  • 19