Home > Software engineering >  How to use sed to replace specific part of a string only?
How to use sed to replace specific part of a string only?

Time:09-01

echo "async_task_payload_manager_scripts_artifact_1.0.0-2" |
sed 's/\_(_scripts_artifact_)./\-(_scripts_artifact_).*/g'

output

async_task_payload_manager_scripts_artifact_1.0.0-2

expected output

async-task-payload-manager_scripts_artifact_1.0.0-2

CodePudding user response:

All _s that occur before _scripts_artifact will be replaced by -s by this sed command:

echo "async_task_payload_manager_scripts_artifact_1.0.0-2" |
sed -e :a -e 's/\(.*\)_\(.*_scripts_artifact\)/\1-\2/; ta'

CodePudding user response:

This might work for you (GNU sed):

sed 's/_/\n/4g;y/_\n/-_/' file

Translate all _'s but the first 3 to newlines.

Translate all _'s to -'s and all newlines to _'s.

CodePudding user response:

Perl to the rescue!

Perl has the lookahead assumption, i.e. you can say "replace _ followed by anything and payload_manager_scripts with a dash":

echo async_task_payload_manager_scripts_artifact_1.0.0-2 \
| perl -pe 's/_(?=.*manager_scripts_artifact)/-/g' 

CodePudding user response:

With your shown samples please try following awk code. Written and tested in GNU awk. This code uses match function of GNU awk. Which allows us to use regex((^.*)(_manager_scripts_artifact_.*) in this case) and create capturing groups which are stored into array(arr in this case) values with index of 1,2,3.... and later on we are retrieving and substituting _ with - in 1st part of array and then printing both elements of array to achieve the expected results.

Here is the Online Demo for used regex to understand capturing groups getting created with it.

##Shell variable
val="async_task_payload_manager_scripts_artifact_1.0.0-2"

awk '
match($0,/(^.*)(_manager_scripts_artifact_.*)/,arr){
  gsub(/_/,"-",arr[1])
  print arr[1] arr[2]
}
' <<<"$val"
  • Related