I'm aware that I can use sed, but I'm trying to figure out if I can do the same thing with grep.

I have the number 36.508 and I want to replace it with 36.62.

grep -v "^36.508" file3.1 | echo "36.62" 

it still prints out 36.508. What is the best option for changing it from 36.508 to 36.62 using grep?

  • For starters, you don't need the quotations. Second, that command works when I try it so perhaps your environment is just different. Lastly, the command doesn't change 36.508 to 36.62. You are telling it to print the lines that don't include 36.508 via grep -v and then piping that to echo 36.52 which just sends 36.52 to stdout. file3.1 is still going to have 36.508 and not 36.62. The only way to actually change it is with sed. – Nasir Riley Mar 31 '18 at 23:46
  • I'm not exactly understand what do you need. Are you need round up all floating point numbers occurrences in file without using of sed? – Yurij Goncharuk Mar 31 '18 at 23:48
  • @NasirRiley I actually suspect that you could abuse grep (in perl mode) to replace it, with a combination of read, lookaheads and lookbehinds. Although I'm not sure if that is "cheating" by using read and ifs. Of course, it's pretty hacky, and definitely something better done with awk, sed, etc. – Sparhawk Apr 1 '18 at 1:34
  • @Sparhawk It isn't possible in the way that he wants to do it. It can be done in your way or in other ways by piping the command but that's unnecessarily convoluted. It's better and much cleaner just to use sed. – Nasir Riley Apr 1 '18 at 1:49
  • @NasirRiley I agree 100% that it's better and cleaner to use sed, but I'm not totally sure what the questioner wants. (They are aware of sed, so it might just be an academic question.) – Sparhawk Apr 1 '18 at 1:50

No, you cannot replace a word with grep: grep looks for lines matching the expression you give it and prints those out (or with -v prints out the lines not matching the expression).

If you want to replace the match, then you need something like sed:

sed 's/36\.508/36.62/' file3.1

or if you want to save it to a file:

sed 's/36\.508/36.62/' file3.1 > file3.1.modified

or if you really want to modify the input file (you'd better be careful with this):

sed -i 's/36\.508/36.62/' file3.1

Did I mention you really want to be careful with this last form?

  • 1
    Probably need to escape the ., too. – Sparhawk Apr 1 '18 at 2:25
  • Yes, thanks - edited. – NickD Aug 23 '19 at 21:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.