Re: sed and variables question
- From: "juicymixx@xxxxxxxxxxxxxx" <juicymixx@xxxxxxxxxxxxxx>
- Date: 20 Mar 2007 19:18:21 -0700
On Mar 18, 11:39 pm, Ed Morton <mor...@xxxxxxxxxxxxxx> wrote:
juicym...@xxxxxxxxxxxxxx wrote:
On Mar 16, 10:41 pm, Ed Morton <mor...@xxxxxxxxxxxxxx> wrote:
Jean-Rene David wrote:
* juicym...@xxxxxxxxxxxxxx [2007.03.17 03:07]:
sed -n '/$rand_text/{g;1!p;};h' "$1"
It's just a matter of proper quoting. For $rand_text to get
expanded, you need double quotes, not single quotes. However
once you have double quotes, you need to watch out for *all*
characters which are special to the shell (i.e. the bang, in
your case):
sed -n "/$pattern/{g;1\!p;};h" "$1"
That's not all. In the example the OP gave, the "pattern" was multiple
lines. You'd need to deal with that too. If someone can interpret what
the jumble of single characters after /$pattern/ actually does, I could
tell you how to do it in awk without having to deal with any of those
complexities...
Ed.
Hi Ed,
this is just a handy sed 'one liner'. All it does is print the line
of text immediatelly before a pattern (or regular expression); However
it does NOT print the line containing the pattern (or regular
expression).
For a one-line regular expression in awk, it'd just be:
awk -v pat="whatever" '$0 ~ pat{print saved}{saved=$0}' file
For a multi-line pattern, you'd either have to read the whole file into
memory by setting RS to some control character that doesn't appear in
your inpur and then split the fields on "\n" by setting FS="\n" or build
an array of lines for the comparison, something like this (untested):
wk -v pat="whatever" 'BEGIN{ np=split(pat,patA,RS) }
$0 ~ patA[np] {
# the current line matches the final line of the pattern.
# See if the preceeding np-1 lines also match. If so the
# whiole pattern is present and saved[0] contains the line
# before the matching lines.
for (i=1; (i < np) && (saved[i] == patA[i]); i++)
;
if (i == np)
print saved[0]}
{saved[idx++]=$0; if (idx > np) idx=0}' file
Regards,
Ed.
Thanks to everyone who helped with this. I have a better
understanding of where sed should be used, and where awk is a better
tool. I'm still learning (and still bound to make silly
mistakes)... Thanks again to everyone.
.
- References:
- sed and variables question
- From: juicymixx@xxxxxxxxxxxxxx
- Re: sed and variables question
- From: Jean-Rene David
- Re: sed and variables question
- From: Ed Morton
- Re: sed and variables question
- From: juicymixx@xxxxxxxxxxxxxx
- Re: sed and variables question
- From: Ed Morton
- sed and variables question
- Prev by Date: Re: Cron question
- Next by Date: Re: insert a line before the first line of a file
- Previous by thread: Re: sed and variables question
- Next by thread: copy files greater than 40 kb size from a folder using single command
- Index(es):
Relevant Pages
|