Home > Software engineering >  find a string in every line of a file then replace another string on the same line using bash
find a string in every line of a file then replace another string on the same line using bash

Time:05-06

here is my script :

#! /bin/bash

# C-band Edit
dqt='"'
str5="polarization=${dqt}2${dqt}"
for x in {3600..4200} do;
    sed -i "/$str5.*$x/s/$x/$((x-600))/" satellites.xml
done

all i want to do is to replace number x with x-600 in between 3600 and 4200 on all lines that have str5 in satellites.xml but the script above gives me syntax error

CodePudding user response:

You don't need to use grep -n to get the line number. You can use a regular expression as the address for a command.

$x-600 won't do subtraction, you need to put it in an arithmetic expression context with $(()).

for x in {3600..4200}
do
    sed -i "/$strAAA.*$x/s/$x/$((x-600))/" file.txt
done

Although running sed 600 times to replace each number is a pretty inefficient way to do it. awk would be a better solution if the number to replace is at a consistent place in the line. E.g. if it's in the 5th field:

awk -v search="$strAAA" '$1 == search { $5 -= 600 }' file.txt > newfile.txt

CodePudding user response:

@Barmar i use bash for sure this is my final state for script

#! /bin/bash

# C-band Edit
dqt='"'
str5="polarization=${dqt}2${dqt}"
for x in {3600..4200} do;
    sed -i "/$str5.*$x/s/$x/$((x-600))/" satellites.xml
done

it gives me syntax error

  • Related