3
2
Contents of source.txt
:
gold green white black blue
yellow magenta brown
tram kilo charlie tango
Hi everyone! I need to solve a mystery.
I'm trying to run a small script to grep a file source.txt
, pipe grep
output to sed
replace a string and store that line in a new file pol.txt
grep -l "gold" source.txt | xargs sed 's/green/red/' > pol.txt
Instead of having the only that line stored in pol.txt
:
gold red white black blue
I have the entire file itself with the string I replaced
gold red white black blue
yellow magenta brown
tram kilo charlie tango
When I remove the option -l
from grep command I have this and of course nothing in pol.txt
sed: can't read gold: No such file or directory
sed: can't read green: No such file or directory
sed: can't read white: No such file or directory
sed: can't read black: No such file or directory
sed: can't read blue: No such file or directory
grep
is needed as a tester and unfortunately " if " is not an option.
What OS are you on? And what was the
source.txt
file saved with? To me this seems like it might be a mixup between carriage returns and line-feeds getting mixed up. – JakeGould – 2016-07-21T00:43:12.587As John1234’s answer shows, you hardly ever need to use
grep
andsed
together —sed
by itself can probably do anything that the two programs can do together. If you have a problem where you have multiple input files and you need to process only the ones that contain “gold”, you should probably explain that; otherwise, people who are trying to answer your question have one hand tied behind their back. (Please do not respond in comments; [edit] your question to make it clearer and more complete.) As Satya Mishra explains,grep -l "gold" source.txt
will outputsource.txt
… (Cont’d) – G-Man Says 'Reinstate Monica' – 2016-07-21T11:37:17.747(Cont’d) … if the file contains the word “gold” (and nothing if it doesn’t). If the only thing that you’re writing into your pipe is the
source.txt
filename, there’s no way the process on the right side of the pipe can know that you want it to process only the lines that contain “gold” unless you build that into the command (as John demonstrates). (His command can be simplified a little, tosed -n '/gold/s/green/red/p' source.txt
. And, if you can writesed 's/green/red/'
, is this really so “frightening” that “it will be a pain” to maintain?) – G-Man Says 'Reinstate Monica' – 2016-07-21T11:37:33.030