0

I'm unable to use the below command using shell script.

awk '{a[NR]=$0} $0~s {f=NR} END {for (i=f-B;i<=f+A;i++) print a[i]}' B=1 A=5 s="5S5SDF" testfile 

Looking for a string "5S5SDF" in testfile.

cat myscript

#!/bin/ksh

echo "The output is"

awk '{a[NR]=$0} $0~s {f=NR} END {for (i=f-B;i<=f+A;i++) print a[i]}' B=1 A=4 s=
 "5S5SDF" testfile

The system doesn't display anything, after i pause break i see error

myscript[5]: 77144447 Quit
myscript[6]: 5S5SDF:  not found

What am i missing?

ShravanM
  • 323
  • 1
  • 7
  • 21
  • See e.g. http://stackoverflow.com/a/19075707/297323 on how to pass an variable into an awk-script. Basically, use `awk -v var="$variable"` – Fredrik Pihl Sep 19 '14 at 09:33
  • 2
    @FredrikPihl Variable assignments in the file list are perfectly valid. And, I believe, even more widely supported than `-v` (that is older). And that's unrelated to the issue here. – Etan Reisner Sep 19 '14 at 09:44
  • 2
    Is that `awk` on one line and does `"5S5SDF"` start a new line? Because if so that's the problem. The shell script sees them as two different commands. – Etan Reisner Sep 19 '14 at 09:44
  • well i'm using tedit and the line accepts till s=' anything i enter after that comes into the second line. how can i solve this? – ShravanM Sep 19 '14 at 09:55
  • used '\' for continuation it worked. thanks Etan Reisner – ShravanM Sep 19 '14 at 10:26
  • @EtanReisner I have another query, if the file doesn't contain "5S5SDF" then the above commands pulls the top rows of a file. why? how can i get blank data if string is not present? – ShravanM Sep 19 '14 at 10:56
  • 2
    When nothing matches `f` is `0`. And `0 - 1` is `-1`. `0 + 5` is `5`. So your loop still fires. You want to add a check for `f` having a non-zero value. But this is also a hugely inefficient way of doing what you want (print N lines after a matching pattern since you store the whole file in memory for no reason). See http://stackoverflow.com/a/17914105/258523 for better solutions. – Etan Reisner Sep 19 '14 at 11:45
  • Stating the screamingly obvious - using an editor that forces you to inject newlines where you don't want them is a terrible idea. Get a new editor! – Ed Morton Sep 19 '14 at 12:24
  • Please update your question with samples of the input file, and the desired output. – John B Sep 19 '14 at 12:59

0 Answers0