7

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?

5 Answers 5

15

You could use sed:

sed -i 's/MyCar on/MyCar off/' path/to/file
Sign up to request clarification or add additional context in comments.

5 Comments

I read about sed but it was so hard to understand specially for a non-english man.
@BehnamSafari, don't worry, it's hard to use for people who have English as their first language too. If you can speak line-noise, you're way ahead of the curve. (But seriously, sed is awesome.)
@ghoti: So true!. FWIW, your link is dead, but here's a great intro to sed.
@Seamus, ah well, it's 8+ years since I posted that comment; one has to expect some churn. Thanks for posting that intro. Here's a link to the last capture of Towers of Hanoi
@ghoti: Yes - SO is becoming like a museum. I wonder what the average life expectancy of a URL is these days? The Towers of Hanoi was fascinating! I didn't know it was called by that name. I got one as a birthday gift when I was a small child - 5 or 6 yo I think... but it was made of wood instead of sed :)
1
sed 's/MyCar on/MyCar off/' >filename

more on sed

Comments

1

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)

Comments

0

try this command when inside the file

:%s/old test/new text/g

Comments

0

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`

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.