-1

This question already has an answer here:

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.

marked as duplicate by steeldriver, Stéphane Chazelas, dhag, techraf, GAD3R Nov 29 '16 at 14:02

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • 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
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.

  • I saw your answer after already posting my comment – Dani_l Nov 29 '16 at 13:07
  • 1
    Note that some awk implementations need the variabl=... to be a separate argument from -v, so awk -v variable=... is more portable than awk -vvariable=.... – Stéphane Chazelas Nov 29 '16 at 14:37
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
  • 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
  • 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
  • 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

Not the answer you're looking for? Browse other questions tagged or ask your own question.