如何从文件中获取特定字符串并将其存储在shell脚本的新文件中?

时间:2016-05-25 08:15:16

标签: linux shell

我有一个sql文件,其中包含此文件中的一些数据,如下所示:

INSERT a=1 , b=2;  
INSERT a=2 , b=10;

就像那么多行我想要获取这些包含" INSERT"关键字直到分号并创建一个新文件并将其保存到新文件中。

使用shell脚本。

2 个答案:

答案 0 :(得分:1)

var LLOCCounter = function() {};

LLOCCounter.prototype.count = function(code) {
  var numberOfLLOC = [];

  code = code.trim().replace(/(=)?=(?!=)/g, function($0, $1){  // Pre-process single =
	  return $1 ? $0 : '_SiNGlE_';
  });
  code = code.replace(/(=)?==(?!=)/g, function($0, $1){  // Pre-process double =
	  return $1 ? $0 : '_DoUbLe_';
  });
  code = code.replace(/(=)?===(?!=)/g, function($0, $1){    // Pre-process triple =
	  return $1 ? $0 : '_TrIpLe_';
  });

  var tokenEquals = code.split("_SiNGlE_");              // Split with the temp tokens
  var tokenDoubleEquals = code.split("_DoUbLe_");
  var tokenTrippleEquals = code.split("_TrIpLe_");


  numberOfLLOC = [
    tokenEquals.length - 1, // 4	=
    tokenDoubleEquals.length - 1, // 5	==
    tokenTrippleEquals.length - 1, // 6	===
  ]

  console.log(numberOfLLOC)
};

contents = "= == ==="
llocCounter = new LLOCCounter();
numberOfLLOC = llocCounter.count(contents);

或使用$ sed -n '/^\s*INSERT/p' data > newfilename $ cat newfilename INSERT a=1 , b=2; INSERT a=2 , b=10;

grep

使用$ grep '^INSERT' data > newfilename $ cat newfilename INSERT a=1 , b=2; INSERT a=2 , b=10;

awk

答案 1 :(得分:0)

cat test.sql 
insert a = 1; b= 2;
delete a, b;
insert d = 8;
insert g = 9;

grep 'insert' test.sql > newfile
cat newfile 
insert a = 1; b= 2;
insert d = 8;
insert g = 9;

这也可以帮到你

^(插入符号) 意味着"线的开头"。所以" ^ a"意味着找到以" a"开头的行。

$(美元符号) 意味着"线的末端"。所以" a $"意味着找到一个以" a"。

结尾的行

例如,此命令在文件myfile中搜索以" s"开头的行。并以" n"结束,并将它们打印到标准输出(屏幕):

cat myfile | grep' ^ s。* n $'