Shell脚本,用于将文件的每一行存储到单独的文件中



我正在尝试将文件(./answer/answerOnly.txt(的行内容获取到单独的文件中。

给定->answerOnly.txt:

Ans1
Ans2
Ans3
Ans4

预期输出->要创建的文件

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

和1.text包含:

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

我尝试过->

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

输出:正在创建空文件

观察:";awk‘NR==$i’;将只接受数字。需要一种"NR==?"接受变量值。

谢谢,非常感谢您的帮助。

为什么不使用split

例如:

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

工作原理:

  • -d使用数值
  • -l按行数拆分,此处为1
  • answerOnly是您的输入文件
  • answer是您的输出文件
  • --additional-suffix=.txtanswer.txt相加
  • --suffix-length添加长度为N的后缀
  • --numeric-suffixes与-d相同,但允许设置起始值

或者。。。使用CCD_ 13。

方法如下:

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

其中"$1"是源文件。

我假设在文件名${i}.txt中,i是行号

那么这会有帮助吗?

#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

最新更新