[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 524
  • Last Modified:

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
0
shalomc
Asked:
shalomc
1 Solution
 
biraCommented:
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
0
 
nociSoftware EngineerCommented:
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<---


0
 
ahoffmannCommented:
sed -e '/foo\.bar/s/^.*$/sunprise/' your-file
0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
James0628Commented:
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
0
 
ahoffmannCommented:
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
0
 
shalomcAuthor Commented:
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
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now