How to change a word in a file using linux shell script

I have a text file with a lot of lines I have a line that has: MyCar on

How can I turn off the car?

+6
source share
4 answers

You can use sed:

sed -i 's/MyCar on/MyCar off/' path/to/file 
+12
source

You can only do this with a shell. This example uses an unnecessary case statement for this particular example, but I turned it on to show how you can enable multiple replacements. Although the code is larger than sed 1-liner, it is usually much faster because it uses only built-in shells (up to 20x for small files).

 REPLACEOLD="old" WITHNEW="new" FILE="tmpfile" OUTPUT="" while read LINE || [ "$LINE" ]; do case "$LINE" in *${REPLACEOLD}*)OUTPUT="${OUTPUT}${LINE//$REPLACEOLD/$WITHNEW} ";; *)OUTPUT="${OUTPUT}${LINE} ";; esac done < "${FILE}" printf "${OUTPUT}" > "${FILE}" 

for a simple case, you can omit the case statement:

 while read LINE || [ "$LINE" ]; do OUTPUT="${OUTPUT}${LINE//$REPLACEOLD/$WITHNEW} "; done < "${FILE}" printf "${OUTPUT}" > "${FILE}" 

Note: ... || ["$ LINE"] ... a bit should prevent the loss of the last line of a file that does not end with a new line (now you know at least one question why your text editor continues to add them)

+1
source
 sed 's/MyCar on/MyCar off/' >filename 

more about sed

0
source

try this command when inside the file

:%s/old test/new text/g

0
source

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


All Articles