-1

I want to loop over a file starting from the n th line using shell sed,I could make it work for an integer (example below starting from line 5), but I want to replace the integer by an sys argument variable : linesToBegin= $1

Here is the code:

sed -n '5,$ p' twitter_ids.txt | while read linecontent
do
            echo $linecontent 
done

When I replace the number 5 by linesToBegin:

sed -n '$linesToBegin,$ p' twitter_ids.txt | while read linecontent

I get an error saying

sed: -e expression #1, char 3: extra characters after comman
Youcef
  • 1,103
  • 2
  • 11
  • 26
  • 1
    Single quotes don't expand variables, double quotes do. – choroba Jul 21 '19 at 10:34
  • You may be starting out on the wrong foot with the shell loop. See [why-is-using-a-shell-loop-to-process-text-considered-bad-practice](https://unix.stackexchange.com/questions/169716/why-is-using-a-shell-loop-to-process-text-considered-bad-practice). Also, using `tail -n +"$linesToBegin"` would make a lot more sense than using `sed` to tail a file. – Ed Morton Jul 21 '19 at 15:21

1 Answers1

0
linesToBegin="$1"
sed -n "$linesToBegin,\$ p" twitter_ids.txt | while read linecontent
do
            echo "$linecontent"
done

Should probably work now. Just need double quotes.

Mihir Luthra
  • 6,059
  • 3
  • 14
  • 39
  • Unfortunately it did not work for me, giving me : sed: -e expression #1, char 1: unknown command: `,' – Youcef Jul 21 '19 at 10:36
  • @goodboy, surprising, works correctly on my machine.. – Mihir Luthra Jul 21 '19 at 10:38
  • Ok, now it is working, the problem was a little space in the assignment in the sys arg variable that i did not notice ! – Youcef Jul 21 '19 at 10:51
  • `echo "$linecontent"` is better, the line can be a special character like `*`. More standard is using curly braces like `echo "${linecontent}"`. – Walter A Jul 21 '19 at 12:49
  • 1
    That should be `while IFS= read -r linecontent`. @WalterA you're right about the quotes but when just referencing scalar variables curly braces are only for when you need to separate the variable name from other alphanumeric text, e.g. `echo "${foo}bar"`, there's no need to use them otherwise. If you were doing a substitution like `echo "${foo#*.}"` or using an array like `echo "${foo[@]}"` then you'd use them but that's not the case here. – Ed Morton Jul 21 '19 at 15:15