简体   繁体   中英

How can I replace a word at a specific line in a file in unix

I've researched other questions on here, but haven't really found one that works for me. I'm trying to select a specific line from a file and replace a string on that line with another string. So I have a file named my_course. I'm trying to modify a line in my_course that starts with "123". on that line I want to replace the string "0," with "1,". Help?

One possibility would be to use sed :

sed '/^123/ s/0/1/' my_course
  • In the first /../ part you just have to specify the pattern you are looking for ^123 for a line starting with 123.

  • In the s/from/to/ part you have specify the substitution to be performed.

Note that by default after substitution the file will be written to stdout. You might want to:

  • redirect the output using ... > my_new_course

  • perform the substitution "in place" using the -e switch to sed

If you are using the destructive in place variant you might want to use -iEXTENSION in addition to keep a copy with the given EXTENSION of the original version in case something goes wrong.

EDIT: To match the desired lined with a prefix stored in a variable you have to enclose the sed script with double quotes " as using single qoutes ' will prevent variable expansion:

sed "/^$input/ s/0/1/" my_course

Have you tried this: sed -e '[line]s/old_string/new_string/' my_course

PS: the [ ] shouldn't be used, is there just to make it clear that you should put the number right before the "s".

Cheers!

In fact, the -e in this case is not necessary, I can write just

sed '<line number>s/<old string>/<new string>/' my_course

This is what worked for me on Fedora 36, GNU bash, version 5.2.15(1)-release (x86_64-redhat-linux-gnu):

sed -i '1129s/additional/extra/' en-US/Design.xml

I know you said you couldn't use line numbers; I don't know how to address that part, but this replaced "additional" with "extra" on line 1129 of that file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM