Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a text file which have lots of lines I have a line in it which is: MyCar on

how can I turn my car off?

like image 704
Behnam Safari Avatar asked Jan 30 '12 12:01

Behnam Safari


People also ask

How do you replace a word in a shell script?

Use Stream EDitor (sed) as follows: sed -i 's/old-text/new-text/g' input.txt. The s is the substitute command of sed for find and replace. It tells sed to find all occurrences of 'old-text' and replace with 'new-text' in a file named input.txt.

How do I replace text in a file?

Replacing text within NotepadOpen the text file in Notepad. Click Edit on the menu bar, then select Replace in the Edit menu. Once in the Search and Replace window, enter the text you want to find and the text you want to use as a replacement.

How do you replace a word in VI Linux?

The simplest way to perform a search and replace in Vim editor is using the slash and dot method. We can use the slash to search for a word, and then use the dot to replace it. This will highlight the first occurrence of the word “article”, and we can press the Enter key to jump to it.


3 Answers

You could use sed:

sed -i 's/MyCar on/MyCar off/' path/to/file
like image 142
knittl Avatar answered Sep 21 '22 06:09

knittl


You can do this with shell only. This example uses an unnecessary case statement for this particular example, but I included it to show how you could incorporate multiple replacements. Although the code is larger than a sed 1-liner it is typically much faster since it uses only shell builtins (as much as 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 the simple case one could omit the case statement:

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

Note: the ...|| [ "$LINE" ]... bit is to prevent losing the last line of a file that doesn't end in a new line (now you know at least one reasone why your text editor keeps adding those)

like image 32
technosaurus Avatar answered Sep 19 '22 06:09

technosaurus


sed 's/MyCar on/MyCar off/' >filename

more on sed

like image 36
Balaswamy Vaddeman Avatar answered Sep 20 '22 06:09

Balaswamy Vaddeman