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 ?
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.
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.
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.
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.
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~
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With