Behnam Safari
Behnam Safari

Reputation: 3071

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?

Upvotes: 7

Views: 17524

Answers (5)

jawad846
jawad846

Reputation: 772

Using sed with variables;

host=$(hostname)
se1=$(cat /opt/splunkforwarder/etc/system/local/server.conf | grep serverName)
sed -i "s/${se1}/serverName = ${host}/g"  /opt/splunkforwarder/etc/system/local/server.conf`

Upvotes: 0

user2607061
user2607061

Reputation: 1

try this command when inside the file

:%s/old test/new text/g

Upvotes: 0

technosaurus
technosaurus

Reputation: 7802

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)

Upvotes: 1

Balaswamy Vaddeman
Balaswamy Vaddeman

Reputation: 8530

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

more on sed

Upvotes: 1

knittl
knittl

Reputation: 265171

You could use sed:

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

Upvotes: 15

Related Questions