Home > other >  How to replace selected words to another word using a shell script
How to replace selected words to another word using a shell script

Time:09-23

I have a shell script which looks like this (myscript.sh)

echo $squad $buildnumber $date > file2.txt

I have 4 squads. I am parsing them to myscript.sh from Jenkins pipeline

those squads are:

DOD
ABCD
UAB_MS
DCF

when script write file2.txt, then it has to replace 2 squads. other 2 should return without replacing.

I have to replace:

UAB_MS, DCF to UAB

let's assume if it parse DCF to script. then expected output would be (file2.txt)

UAB 115 2022-09-23

this is what i tried (myscript.sh)

if [ $squad == 'DCF' ]
then
newsquad= sed -i 's/DCF/UAB/g'

elif [ $squad == 'UAB_MS' ]
then
newsquad= sed -i 's/UAB_MS/UAB/g'

else
newsquad=$squad
fi

echo $newsquad $buildnumber $date > file2.txt

Can someone help me to figure out this? Thanks in advance!

Note: I am not allowed to use general purpose scripting language (JavaScript, Python etc).

CodePudding user response:

You can join the commands to one line. I added double quotes (no difference here), for future work it is good to get used to that. I also added ^ in the replacement, so it will only match the start of the line (in $squad). That way a string "DCF" in $buildnumberwill not be replaced.

echo "$squad $buildnumber $date" | sed 's/^DCF/UAB/; s/^UAB_MS/UAB/' > file2.txt

CodePudding user response:

Based on your example, this should works too.

file='file2.txt'
IFS='
'
for what in $squad; do
    if [ "$what" = 'UAB_MS' ] || [ "$what" = 'DCF' ]; then
        echo "UAB $buildnumber $date"
    else
        echo "$what $buildnumber $date"
    fi
done > "$file"

CodePudding user response:

I think you can update your script making use of sed in a sub shell and remove the spaces when assining values to variables.

Also remove -i from the sed commands as that means editing a file inplace

#!/bin/bash

squad="DCF"
buildnumber="115"
date="2022-09-23"

if [ $squad == 'DCF' ]
then
newsquad=$(sed 's/DCF/UAB/g' <<< "$squad") 
elif [ $squad == 'UAB_MS' ]
then
newsquad=$(sed 's/UAB_MS/UAB/g' <<< "$squad")
else
newsquad=$squad
fi
echo "$newsquad $buildnumber $date" > file2.txt

But what you might also do is use an alternation | with sed to replace either DCF or UAB_MS with UAB

echo "$squad $buildnumber $date" | sed 's/^\(DCF\|UAB_MS\)/UAB/' > file2.txt

Output

UAB 115 2022-09-23
  • Related