Link to home
Start Free TrialLog in
Avatar of Shalom Carmel
Shalom CarmelFlag for Israel

asked on

A sed question

Hello Experts,
I want to use sed to find the first occurence of a particular string, for example "foo.bar", in a file.
When the string is found, the entire line it is in is to be replaced by a constant text, for example "surprise".

Example:

chicago 999 123
denver 874 99676 X
chicago 654 foo.bar 9867
apache 8794 bar.bar 8994
jersey soprano foo.bar 19


foo.bar is on the 3rd and 5th lines. only the first occurence will be transformed to "surprise".

chicago 999 123
denver 874 99676 X
surprise
apache 8794 bar.bar 8994
jersey soprano foo.bar 19


ShalomC
Avatar of bira
bira

This script will do the work, altough not using sed.
create a file named "yourfile" with the lines

chicago 999 123
denver 874 99676 X
chicago 654 foo.bar 9867
apache 8794 bar.bar 8994
jersey soprano foo.bar 19

then run the script below

clear
flag=0
while read x
do
a=`echo $x |grep foo.bar`
  if [ $? = 0 -a $flag = 0 ] ; then
         echo surprise
         flag=1
         else echo $x
  fi
done < yourfile
Avatar of noci
Using the ed commands (like vi esc: commands)

---8<---
#!/bin/bash
ed -s yourfile <<EOX 2>/dev/null
/foo.bar/s/^.*$/surprise/
%p
Q
EOX
---8<---


ASKER CERTIFIED SOLUTION
Avatar of ahoffmann
ahoffmann
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ahoffmann,

 But that would change every line with foo.bar in it (Wouldn't it?) and they only wanted to change the first one.


 ShalomC,

 sed probably isn't the best tool for this.  It's just not designed to change a single occurrence of a target string like this.

 James
oops, missed the "first one"
this is a academic requirement for sed, you better use awk or perl for that
  awk '/foo\.bar/{if(f==0){print "sunprise";f++;next}}{print}' your-file
Avatar of Shalom Carmel

ASKER

thanks guys,
this was supposed to work on an AS400 server - IBM did not port awk nor perl.
eventually it turned out that there can be only one occurence of the string, so the points go to ahoffmann

ShalomC