How to replace part of a string with sed?

I have a file that contains many lines (line separator ~). In each line, I have many elements separated by the separator '*'. I want to do this, I will have a line that starts with the line TRN in my file. It may contain 4 (including TRN) or more data points. Sort of,

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

I want to replace the fourth data point from these rows with abc123. i.e,

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

I tried using sed command with regex

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

But the whole line is replaced with abc123.

Is it possible to change only the 4th data channel with the sed command?

+5
source share
5 answers

Using the GNU Command:

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

Output:

 TRN*1*S521000035*abc123~ TRN*1*S521000035*abc123*787989800~ 
+2
source

sed is your friend.

Try this test version:

 $ sed "s/^\(TRN[*][^*][^*]*[*][^*][^*]*[*]\)[^*][^*]*\(.*~\)/\1abc123\2/" afile.txt TRN*1*S521000035*abc123~ TRN*1*S521000035*abc123*787989800~ 

You might want to read the man pages for more information on regexp and sed

+2
source

This may work for you (GNU sed):

 sed 's/[^*~]\+/abc123/4' file 

Replace the fourth occurrence of something that does not contain ~ or * with abc123 .

+1
source

AWK should do the trick in a rather concise and readable way. FS modifies the field delimiter so that you can determine where you want it to break inside the line.

 $ awk 'BEGIN { FS="*|~" }{ sub($4, "abc123"); print $0}' file.txt TRN*1*S521000035*abc123~ TRN*1*S521000035*abc123*787989800~ 
0
source

While you can do this with sed , it's much easier to achieve the desired effect with awk . The awk program is especially useful for analyzing and transforming table-structured data, as in your case:

 awk -F'*' -v OFS='*' '{$4 = "abc123"; print}' 

It reads:

 awk Run the program awk -F'*' Use the * as a field delimiter on input -v OFS='*' Use the * as a field delimiter on output '{ On each record … $4 = "abc123"; … set the 4th field to "abc123" print … and print the curent record }' 

In this example, it is also easy to expand the selective replacement of the 4th field depending on the value of other fields.

0
source

Source: https://habr.com/ru/post/1244643/


All Articles