user2854333 user2854333 - 5 months ago 30
Perl Question

Inserting a line in text file through perl is failing

I am trying to insert a new row on 2nd line of text file using perl . But it keeps failing.

I am using below command to achieve the same.

perl -ni -e "print; print \"permissibleCars = [ ${part[*]} ]\n\" if $. == 2" query/containerId_count.js


But I keep getting error :--

root@vm-test-001:~/mongosearch# distinct_array=`sed ':a;N;$!ba;s/\n/ /g' output/ontainerId_distinct.txt`
root@vm-test-001:~/mongosearch# declare -a arr=($distinct_array)
root@vm-test-001:~/mongosearch# batchsize=1
root@vm-test-001:~/mongosearch# IFS=,
root@vm-test-001:~/mongosearch# part=( "${arr[@]:i:batchsize}" )
root@vm-test-001:~/mongosearch# echo $part
"C:00000092666270:53882159774"
root@vm-test-001:~/mongosearch# perl -ni -e "print; print \"permissibleCars = [ ${part[*]} ]\n\" if $. == 2" query/containerId_count.js
Bareword found where operator expected at -e line 1, near ""permissibleCars = [ "C"
(Missing operator before C?)
String found where operator expected at -e line 1, near "53882159774" ]\n""
(Missing operator before " ]\n"?)
syntax error at -e line 1, near ""permissibleCars = [ "C"
Illegal octal digit '9' at -e line 1, at end of line
Execution of -e aborted due to compilation errors.


Can you help me with same ?

Regards

Answer Source

Try this:

export PARTS=${part[*]}
perl -lni -e 'print; print "permissibleCars = [".join(",",split/ /,$ENV{PARTS})."]" if $. == 2' query/containerId_count.js