将文本插入文件,如添加数组元素

Inserting a text into a file, like adding an array element

我有一个 JavaScript 文件,如下所示。

Me.dat

var fruit = [
 "Apple",
 "Mango",
 "Orange"
];

var players = [
 "Sachin",
 "Dhoni",
 "Kapil Dev"
];

我需要向这些数组中的任何一个动态添加一个元素。(实际上在文件中)。

根据工作状态,我会插入到相应的数组中。

比如说,

addMe "Grapes" "fruits"

将创建一个文件,

var fruit = [
 "Apple",
 "Mango",
 "Orange",
 "Grapes" ---------Added newly!!!
];

var players = [
 "Sachin",
 "Dhoni",
 "Kapil Dev"
];

所以,我必须在文件的第 5 行插入文本 "Grapes"。


这就是我现在拥有的..

我的脚本:

SEARCHTERM="fruits";
TO_BE_ADDED="Grapes";
#take the start line number and end linenumer of the array..
startlinenum=`grep -n $SEARCHTERM me.dat | cut -d ":" -f1 | head -1`;
endlinenum=`tail +$startlinenum me.dat | grep -n "]" | head -1 | cut -d ":" -f1`;
endlinenum=`expr $startlinenum + $endlinenum - 2`;

echo "\"$TO_BE_ADDED\"" > to_be_added.dat;

echo "ENd line is : ${endlinenum}";

sed "${endlinenum}r to_be_added.dat" me.dat

我得到了输出

var fruits = [
 "Apple",
 "Mango",
 "Orange" ------ How would I remove this Comma ? :(
"Grapes" ------ Added Correctly....
];

我做的对吗?或者有更简单的方法吗?

请帮忙。我将如何删除前面代码段中提到的逗号。

这会破坏您的格式(将已修改记录中的所有白色space 替换为单个 space),但也许这会有所帮助:

$ TOBEADDED=banana
$ SEARCHTERM=fruit
$ awk '/var '$SEARCHTERM'/{$(NF-1)=$(NF-1)", \"'$TOBEADDED'\""}1' RS= Me.dat
var fruit = [ "Apple", "Mango", "Orange", "banana" ];
var players = [
        "Sachin",
        "Dhoni",
        "Kapil Dev"
];

修改解决方案以恢复格式相当容易,但这样做会掩盖解决方案,所以我将保持原样。

使用 GNU awk for gensub():

$ gawk -v add="Grapes" -v tgt="fruit" -v RS= -v ORS="\n\n" -v FS="\n" '
  ~" "tgt" "{[=10=]=gensub(/(([ \t]+)"[^"]+")(\n];)/,"\1,\n\2\""add"\"\3","")}1
' Me.dat
var fruit = [
 "Apple",
 "Mango",
 "Orange",
 "Grapes"
];

var players = [
 "Sachin",
 "Dhoni",
 "Kapil Dev"
];