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

时间:2015-02-27 18:04:21

标签: shell unix sed ksh

我有一个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"
];

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


这就是我现在所拥有的......

我的剧本:

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....
];

我在这里做对了吗?或者有更简单的方法吗?

请帮忙。如何删除我在上一个代码段中提到的逗号。

2 个答案:

答案 0 :(得分:2)

这将破坏您的格式(用一个空格替换修改记录中的所有空格),但这可能有用:

$ 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"
];

修改解决方案以重新放入格式是相当容易的,但这样做会使解决方案变得模糊,所以我会保持原样。

答案 1 :(得分:1)

用于gensub()的GNU awk:

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

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