Reputation: 191
I would like to replace the second entry of all (space or tab-separated) lines containing a specific string. In the following text
1078.732700000 0.00001000 1 0 0 39 13 27 0 0 0 40 14 26 81SaWoLa.43 BAD LABEL, REASSIGNED
-1077.336700000 0.00001000 1 0 0 45 12 34 0 0 0 46 13 34 81SaWoLa.48 BAD LABEL
I would like to replace 0.00001000
by 0.00005214
(searching for the string 81SaWoLa
). The result should be
1078.732700000 0.00005214 1 0 0 39 13 27 0 0 0 40 14 26 81SaWoLa.43 BAD LABEL, REASSIGNED
-1077.336700000 0.00005214 1 0 0 45 12 34 0 0 0 46 13 34 81SaWoLa.48 BAD LABEL
Could you please help me how to perform it?
Upvotes: 1
Views: 98
Reputation: 47119
Use awk:
$ awk '/pattern/ { $2 = "new string." }; 1' input.txt
In your case:
$ awk '/81SaWoLa/ { $2 = "0.00005214" }; 1' input.txt
# ^^^^^^^^^^ ^^^^^^^^^^^^^^^^^ ^
# For lines Replace second Print each line, same as:
# matching column with ``{ print $0 }''. ``$0''
# 81SaWoLa ``0.00005214'' contains the whole line.
Use -v name=val
to specify a variable:
$ awk -v pat="81SaWoLa" \
-v rep="0.00005214" \
'$0 ~ pat { $2 = rep }; 1' input.txt
Upvotes: 1
Reputation: 4043
You may use awk
to achieve your goal more easily.
$ awk '/81SaWoLa/{$2="0.00005214"}1' file
1078.732700000 0.00005214 1 0 0 39 13 27 0 0 0 40 14 26 81SaWoLa.43 BAD LABEL, REASSIGNED
-1077.336700000 0.00005214 1 0 0 45 12 34 0 0 0 46 13 34 81SaWoLa.48 BAD LABEL
With the variables to be used, used the command as followed,
$ var1=81SaWoLa
$ var2=0.00005214
$ awk -v var1=$var1 -v var2=$var2 '$0 ~ var1{$2=var2}1' file
1078.732700000 0.00005214 1 0 0 39 13 27 0 0 0 40 14 26 81SaWoLa.43 BAD LABEL, REASSIGNED
-1077.336700000 0.00005214 1 0 0 45 12 34 0 0 0 46 13 34 81SaWoLa.48 BAD LABEL
Upvotes: 2
Reputation: 1270
Try this for GNU sed
:
$ cat input.txt
1078.732700000 0.00001000 1 0 0 39 13 27 0 0 0 40 14 26 81SaWoLa.43 BAD LABEL, REASSIGNED
-1077.336700000 0.00001000 1 0 0 45 12 34 0 0 0 46 13 34 81SaWoLa.48 BAD LABEL
$ sed -r '/81SaWoLa/s/^([^ \t]+[ \t]+)[^ \t]+(.*)/\10.00005214\2/' input.txt
1078.732700000 0.00005214 1 0 0 39 13 27 0 0 0 40 14 26 81SaWoLa.43 BAD LABEL, REASSIGNED
-1077.336700000 0.00005214 1 0 0 45 12 34 0 0 0 46 13 34 81SaWoLa.48 BAD LABEL
Upvotes: 2