0

Suppose I have these in a file called test:

u001:x:comp111:mark_henry
u002:x:comp321:zack_mike
u003:x:comp132:chris_white

And I want to open that file go to the line that has chris_white and change it to chris_brown so it becomes u003:x:comp132:chris_brown. I'm thinking to use the sed command to do so but I'm not sure how.

Cyrus
  • 84,225
  • 14
  • 89
  • 153
  • This has been asked and answered so many times you have to make an effort to avoid an answer. Here is a small sampling of duplicates: [Using 'sed' to find and replace](https://unix.stackexchange.com/q/159367/56041), [How can I replace a string in a file(s)?](https://unix.stackexchange.com/q/112023/56041), [Find and replace text within a file using commands](https://askubuntu.com/q/20414), [Using grep and sed to find and replace a string](https://stackoverflow.com/q/6178498/608639), [Replace substring with sed](https://stackoverflow.com/q/14194702/608639), etc. – jww May 13 '18 at 17:50
  • I'm baffled someone upvoted this question since an upvote indicates *"this question shows research effort; it is useful and clear"*. – jww May 13 '18 at 17:52

2 Answers2

1

Using sed, below method can replace all occurrences of chris_white to chris_brown without opening the file test.

sed -i -e 's/chris_white/chris_brown/g' test

If you want to open the file test in vi editor and replace, then follow the below steps,

1) vi test

2) Type :%s/chris_white/chris_brown/g

3) Press Enter

This will replace all occurrences of chris_white to chris_brown in your file test.

Eby Jacob
  • 1,418
  • 1
  • 10
  • 28
  • I'm not sure if `-i` option would work in all the Unix OS, because in HP-UX it's showing as `sed: illegal option -- i`, what if `sed 's/chris_white/chris_brown/g' test_1` be redirected to a new file just to make the changes permanent into a new file like `-i` option would do. – User123 May 13 '18 at 17:00
0

With vi you need more effort than with the basic ed.

echo "s/chris_white/chris_brown/
w
q" | ed -s test

You can use printf for writing the lines as parameters:

printf "%s\n" "s/chris_white/chris_brown/" w q | ed -s test
Walter A
  • 19,067
  • 2
  • 23
  • 43