I will leave it as a memo for memorandum purposes.
-I want to save a file in units of one line and the file names are divided by serial numbers. ・ For serial numbers, I want to apply zero padding so that the display order is appropriate. -The file to be split was about 4000 lines **-The character string in the division target contains "", and I want to leave it as it is ← 2020/03/13 (Fri) Addendum **
It was kind of troublesome to leave the file as a shell script, so I wrote it so that it would be completed with just the command. (In the end, it seems that the contents written to the shell file have not changed at all ...)
$ bash --version
GNU bash,Version 4.4.20(1)-release (x86_64-pc-linux-gnu)
$ cat /etc/os-release
NAME="Ubuntu"
VERSION="18.04.4 LTS (Bionic Beaver)"
Before improvement
count=1 ; load_target="hogehoge.txt" ; cat ${load_target} | while read line ; do echo ${line} > "${load_target}_`printf \"%04d\" ${count}`.txt" ; count=`expr ${count} + 1` ; done
In the above, if "" is included in the divided character string, it will be read as an escape and erased. (I was dealing with data that contains HTML tag information in the value part of json format, and it actually happened ...)
** If you don't want to be erased, you can use the -r
option of the read
command **
After improvement
count=1 ; load_target="hogehoge.txt" ; cat ${load_target} | while read -r line ; do echo ${line} > "${load_target}_`printf \"%04d\" ${count}`.txt" ; count=`expr ${count} + 1` ; done
Regarding the extension and 0 padding part at the time of output, it seems cool to crush according to the number of lines of the read source file if you do it while extracting the information of variable expansion and read source file with a little more ingenuity. For the time being, the above has been solved, so I hope I can improve it later.
With One Liner, there are even more elegant ways to write! !! I would be grateful if you could give us your opinion for later studies. .. ..
Recommended Posts