home *** CD-ROM | disk | FTP | other *** search
- Path: sparky!uunet!spool.mu.edu!uwm.edu!psuvax1!ukma!cs.widener.edu!dsinc!phent!kkress
- From: kkress@phent.UUCP (Kenneth R. Kress)
- Newsgroups: comp.unix.shell
- Distribution: world
- Subject: Re: Substituing using sed, ...
- Keywords: sed awk substituting
- Message-ID: <9212158153@phent.UUCP>
- Organization: That's Entertainment BBS
- Date: Tue, 15 Dec 92 22:06:54 EST
- Lines: 63
-
- Uwe Waldmann writes:
- > In article <1992Dec14.042422.22897@candle.uucp>, root@candle.uucp
- > (Bruce Momjian) writes:
- > > Here is a sample file:
- > >
- > > acaX csacacXcascsc
- > > "cscaXcacsXcs" csaXc "X" caX
- > > Xaca Xcaca ca "caXcas" ccaX cacs
- > >
- > > I want to use sed to replace X with another character, but only if the X
- > > does not appear within quotes. The quoted strings do not extend across
- > > new-lines.
- >
- > That's easy:
- >
- > #!/bin/sh
- > sed -e '
- > s/^/\
- > /
- > : a
- > s/\(\n[^"]*\)X/\1Y/
- > t a
- > /\n.*".*"/ {
- > s/\n\([^"]*\)"\([^"]*\)"/\1"\2"\
- > /
- > t a
- > }
- > s/\n//
- > ' ${1+"$@"}
- >
- Uwe Waldmann,
- I was unable to test your solution because my version of sed
- gave me pattern overflow errors. And I was unable to decipher your
- technique. But trying to understand it suggested several other
- strategies.
- If Bruce Momjian doesn't mind deconstructing his original file,
- one could do:
- tr -s ' ' '\n' datafile | # every word to a line
- sed 's/ //' | # remove tabs
- sed '/^[^"]/s/X/Y/g' # if line has no quote
- # do the translation
- And this unsatisfactory solution led me to the solution I
- should have thought of first:
- awk '
- { # do this for every line
- for (i = 1; i <= NF; i++) { # loop through words on line
- if ( $i !~ /\"/) { # not quoted
- # gsub (/X/,"Y",$i ) # substitute Y for X
- printf ("%s", $i ) # print out word
- } else { # else
- printf ("%s", $i ) # print out word
- }
- } # line is done, so
- printf "\n" # print newline
- }'
- This requires nawk or gawk.
- Ken.
- ===================================================================
- Ken Kress, Glenside, PA * dsinc!phent!kkress
- Daring ideas are like chessmen moved forward;
- they may be beaten, but they may start a winning game.
- Johann Wolfgang von Goethe
- -------------------------------------------------------------------
-