0

I have a script like this

#!/bin/ksh
echo "Enter the matching pattern"
read pattern
path= /home/siva/
echo "Navigating to $path"
cd $path
cat filename|awk '/$pattern/ {for (i=1; i<=10; i++) {getline;print}}'

i am not able to get the entered $pattern when i execute the script.

fedorqui
  • 7,861
  • 7
  • 36
  • 74
Siva
  • 9
  • Try to format your question. – Kalavan Nov 29 '16 at 13:06
  • 2
    You mean something like awk -v pattern=$pattern '/$pattern/ {for (i=1; i<=10; i++) {getline;print}}' ? please try to edit your code so it's readable – Dani_l Nov 29 '16 at 13:06
  • 1
    @Dani_l no, this would look for a literal $pattern. Instead, you have to say $0 ~ pattern. In general, you cannot use variables within / / because awk does not have a way to distinguish them from literal text. – fedorqui Nov 29 '16 at 13:08

2 Answers2

1
echo | awk -v variable='This is variable!' 'END{print variable}'

You pass variables with -v keyword. And don't use $ for variable - it is not a bash. Awk uses $ to access a field.

Kalavan
  • 666
0
#!/bin/ksh
echo "Enter the matching pattern"
IFS= read -r pattern
path=/home/siva/
echo "Navigating to $path"
cd "$path" || exit
awk -v pattern="$pattern" '$0 ~ pattern{for (i=1; i<=10; i++) {getline;print}}' filename
  1. Use awk -v to pass variables into the awk script
  2. cat is unnecessary - awk can handle files directly
Dani_l
  • 4,943
  • awk -v pattern=$pattern '/$0 ~ pattern/ {for (i=1; i<=10; i++) {getline;print}}' filename' - This doesn't work, – Siva Nov 29 '16 at 13:19
  • Try without the slashes, as per my last edit – Dani_l Nov 29 '16 at 13:23
  • Dani... Perfect. That worked!! – Siva Nov 29 '16 at 13:24
  • What should i do to get the matching pattern also displayed in results? – Siva Nov 29 '16 at 13:26
  • 1
    Using -v mangles backslash characters, using environment variables and ENVIRON["the_variable"] in awk is a better approach considering that regular expressions often contain backslash characters – Stéphane Chazelas Nov 29 '16 at 13:31
  • @StéphaneChazelas -v example: a=aaa;echo | awk -va=$a '{print a}' However I can't seem to get it to work with ENVIRON["a"] - neither a=aaa;echo | awk 'BEGIN{a=ENVIRON["a"]} {print a}' nor a=aaa;echo | awk '{print ENVIRON["a"]}' works – Dani_l Nov 29 '16 at 14:03
  • 2
    a=aaa defines a shell variable. You need to export it if you want it passed as an environment variable to awk, or use a=aaaa awk 'BEGIN{print ENVIRON["a"]}'. See the dup question for details. – Stéphane Chazelas Nov 29 '16 at 14:28