Search for a pattern and if it exists change some other text on the line
I am very new to sed and cannot seem to get my command to work. I am trying to search each line for the value 'onnection' and if it exists anywhere in the line change Abc to Xyz and write the line to a new file which is a parameter passed to the shell. My code currently looks like this
file="first_file.exp" sed -n "/onnection/p" $file|sed -e "s/_Abc/_Xyz/g" $file > "$file_test1_parsed" What am I doing wrong? It is changing all occurrences of Abc not just the lines that have connect in them. TIA, Kathy |
You don't need 2 sed parts, have a look at this:
Code:
sed '/onnection/s/Abc/Xyz/g' $file You can tell sed to use line or pattern ranges as well: Code:
sed '4,$s/X/Y/g' # Change X to Y from line 4 to last line Sed resources: |
What's the actual error?
Try this version: Code:
file="first_file.exp" |
@konsolebox: Why 2 piped sed commands in the first place?
|
@druuna I missed your post as I had my focus on the variables and jumped quickly on it sorry. After making a quick notice I just made a quick edit of my answer.
Anyway I think you should adjust the command to this: Code:
sed -n '/onnection/{ s/Abc/Xyz/g; p; }' "$file" |
And I focussed too much on the range stuff.
If only the lines need to be printed that contain onnection, it can be done like this (simpler?) as well: Code:
sed -n '/onnection/s/Abc/Xyz/gp' $file |
Quote:
|
Thanks all. Great suggestions! I do want all the lines in the file not just the ones I have changed.
|
What would I change in sed -n '/onnection/s/Abc/Xyz/gp' $file to get all the lines from $file to newfile with my changes?
|
Sed has a -i for in place changes (changes the original file):
Code:
sed -i -n '/onnection/s/Abc/Xyz/gp' $file Code:
sed -n '/onnection/s/Abc/Xyz/gp' $file > $newfile |
I tried -i but I get sed: illegal option -- i
When I use the syntax suggested above sed -n '/onnection/s/Abc/Xyz/gp' $file > $newfile all I get in newfile are the changed lines and I want newfile to contain the whole file containing the changed and unchanged lines. |
Quote:
Code:
sed '/onnection/s/Abc/Xyz/g' "$file" > "$newfile" |
Got it! Thanks all. I am all set.
|
Welcome. Glad I was able to help, miss :)
|
By the way, as for the actual error in the OP:
Code:
sed -n "/onnection/p" $file | sed -e "s/_Abc/_Xyz/g" $file > "$file_test1_parsed" (Although as shown you you only really need a single command.) PS: Don't forget to quote all of your variables. http://mywiki.wooledge.org/Arguments http://mywiki.wooledge.org/WordSplitting [url]http://mywiki.wooledge.org/Quotes[url] Edit: Quote:
|
All times are GMT -5. The time now is 11:41 AM. |