0

This is a small portion of a huge script. I am trying to extract particular lines from a file and append it to another file. I tried the following command in the shell.

 cat "temp.xml" | awk 'NR >= 1 && NR <= 100' >> output

This works fine. But when I did this inside a shell script, it shows an error with awk.

The script is,

#!/bin/bash
line_start=1
line_end=100
content=$((cat "$1" | awk 'NR >= $line_start && NR <= $line_end'))
echo $content >> output

and the error is,

dev-005~# ./copy.sh temp.xml
./copy.sh: line 4: cat "temp.xml" | awk 'NR >= 1 && NR <= 100': syntax error: invalid arithmetic operator (error token is ""temp.xml" | awk 'NR >= 1 && NR <= 100'")

I don't understand what's causing the error.

Ezio
  • 175
  • 6
  • ... and replace `$((...))` by `$(...)`. – Cyrus Jun 22 '16 at 17:24
  • bash cannot expand `$line_end` in single quotes and `awk` doesn't know what it is. Define it as an awk variable with `-v`. – karakfa Jun 22 '16 at 17:28
  • @karakfa but in the error, the `$line_start` and `$line_end` were expanded correctly – Ezio Jun 22 '16 at 17:29
  • @cyrus When I used `$(...)` the error is gone, but the `$content` is empty – Ezio Jun 22 '16 at 17:31
  • 1
    `content=$(cat "$1" | awk -v s=$line_start -v e=$line_end 'NR >= s && NR <= e')` – Cyrus Jun 22 '16 at 17:34
  • @Ezio, yes do both changes `$(...)` and assign `awk` variable. In the awk script if you replace the content with `print $line_start` you'll see it won't print. `$((.))` creates a different context. – karakfa Jun 22 '16 at 17:37
  • @cyrus Thanks ! that worked. If I do `cat "$1" | awk -v s=$line_start -v e=$line_end 'NR >= s && NR <= e' >> output` I get the exact lines in the output file. But `content=$(cat "$1" | awk -v s=$line_start -v e=$line_end 'NR >= s && NR <= e'); echo $content >> output` removes the new line character from the input. So, the 100 lines are copied into a single line. Could you please tell me why is that happening ? – Ezio Jun 22 '16 at 17:44
  • Replace `echo $content` by `echo "$content"`. See: [When to wrap quotes around a variable](http://stackoverflow.com/q/10067266/3776858) – Cyrus Jun 22 '16 at 17:48

0 Answers0