Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can one replace a part of a line with sed?

Tags:

regex

bash

sed

I have a file which contains many lines(line delimiter is ~). Each line,I have many elements which is seperated by a delimiter '*'. What I want to do is , I will be having a line that starts with string TRN in my file. It can have 4(including TRN) or more data points in it. Something like,

TRN*1*S521000035*1020494919~
TRN*1*S521000035*1020494919*787989800~

I want to replace the fourth data point from this lines to abc123. ie,

TRN*1*S521000035*abc123~
TRN*1*S521000035*abc123*787989800~

I tried using sed command with regular expression

sed -i 's/^TRN\*(.*)\*(.*)\*(.*)$/abc123/g' file.txt 

But the whole string is getting replaced to abc123.

Is it possible to change only its 4th datapoint using sed command ?

like image 440
Nimmi Mathew Avatar asked Mar 08 '16 07:03

Nimmi Mathew


People also ask

How do you replace a line using sed?

The sed command can be used to replace an entire line with a new line. The "c" command to sed tells it to change the line. The sed command can be used to convert the lower case letters to upper case letters by using the transform "y" option.

Which sed command is used for replacement?

Replacing all the occurrence of the pattern in a line : The substitute flag /g (global replacement) specifies the sed command to replace all the occurrences of the string in the line.

Can you use sed on a string?

The sed command is a common Linux command-line text processing utility. It's pretty convenient to process text files using this command. However, sometimes, the text we want the sed command to process is not in a file. Instead, it can be a literal string or saved in a shell variable.

How do you insert a sed line after a pattern?

Insert a line in a File You have to use the “-i” option with the “sed” command to insert the new line permanently in the file if the matching pattern exists in the file.


1 Answers

Using GNU sed:

$ sed -r -i 's/^((\w+\*){3})\w*(.*)/\1abc123\3/g' file.txt

Output:

TRN*1*S521000035*abc123~
TRN*1*S521000035*abc123*787989800~ 
like image 96
Ahsanul Haque Avatar answered Sep 28 '22 12:09

Ahsanul Haque