Search code examples
linuxstringfilegrepcentos

Linux get part of line's text if matched string in files


In Linux, I have a file test.log that is similar to this:

2021/11/18 17:19:18,034 INFO {"queueName":"queue/RequestQueue",{"threadName":"WorkManager(2)-702","correlationID":"b67601e81bfd","requestData":"TYPE_1, REQUEST 1"}
2021/11/18 17:19:18,036 INFO {"queueName":"queue/ResponseQueue","correlationID":"TMYHxIyeYo","responseData":"TYPE_1, RESPONSE 1"} 
2021/11/18 17:19:18,038 INFO {"queueName":"queue/RequestQueue",{"threadName":"WorkManager(2)-885","correlationID":"j9BNzbbv3E","requestData":"TYPE_2, REQUEST 2"}
2021/11/18 17:19:19,172 INFO {"queueName":"queue/RequestQueue",{"threadName":"WorkManager(2)-183","correlationID":"d29d2d7cf5a4","requestData":"TYPE_1, REQUEST 3"}
2021/11/18 17:19:20,784 INFO {"queueName":"queue/esbRequestQueue",{"threadName":"WorkManager(2)-762","correlationID":"4235eba2765a","requestData":"TYPE_1, REQUEST 4"}

I want to search through all lines of this file and get the lines that have the string ["requestData":"TYPE_1] and write all of the requestData's content to another file called type_1.txt. Each matching line in the test.log file will be written to one line in the type_1.txt file. Below is my expected result in the type_1.txt file:

TYPE_1, REQUEST 1
TYPE_1, REQUEST 3
TYPE_1, REQUEST 4

My question is are there commands that can do this? I'm new to Linux so please help me with this.


Solution

  • Try this command:

    grep -Po '(?<="requestData":")TYPE_1[^"]*' test.log > type_1.txt