2

I wrote a code and it works great but I need to use variables instead static numbers for scopes 8 and 16

cat /etc/passwd | sed '/^#/d' | sed -n 'n;p' | sed 's/:\(.*\) //g' | sed 's/ /,/g' | sed 's/\(.*\),/\1./' | sort -r | sed 's/*rav://g' | sed "s/:.*//" | rev | sed -n -e '8,16p' | xargs | sed -e 's/ /, /g' | sed '/:[0-9]*$/ ! s/$/./'

I've changed the code to

cat /etc/passwd | sed '/^#/d' | sed -n 'n;p' | sed 's/:\(.*\) //g' | sed 's/ /,/g' | sed 's/\(.*\),/\1./' | sort -r | sed 's/*rav://g' | sed "s/:.*//" | rev | sed -n -e '$FT_LINE1,$FT_LINE2+p' | xargs | sed -e 's/ /, /g' | sed '/:[0-9]*$/ ! s/$/./'

but I got a error

sed: 1: "$FT_LINE1,$FT_LINE2p": invalid command code F
codeforester
  • 39,467
  • 16
  • 112
  • 140
Vasyl Kozhushko
  • 83
  • 3
  • 11
  • Beware of "useless use of cat" and save a process by making the first command: `sed '/^#/d' < /etc/passwd` – Gary_W Jul 25 '17 at 17:00

2 Answers2

1

Surround your variables with curly braces so the shell knows where the variable name ends:

sed -n -e "${FT_LINE1},${FT_LINE2}p"

EDIT - D'oh I can't believe I missed the single quotes. They need to be double quotes as others have pointed out so variable substitution will occur.

Gary_W
  • 9,933
  • 1
  • 22
  • 40
  • 1
    Still the same cat /etc/passwd | sed '/^#/d' | sed -n 'n;p' | sed 's/:\(.*\) //g' | sed 's/ /,/g' | sed 's/\(.*\),/\1./' | sort -r | sed 's/*rav://g' | sed "s/:.*//" | rev | sed -n -e '${FT_LINE1},${FT_LINE2}p' | xargs | sed -e 's/ /, /g' | sed '/:[0-9]*$/ ! s/$/./' Error sed: 1: "${FT_LINE1},${FT_LINE2}p ": invalid command code F – Vasyl Kozhushko Jul 25 '17 at 17:21
1

Variables enclosed inside single quotes are not expanded by shell and hence your sed command sees the argument $FT_LINE1,$FT_LINE2p literally. Use double quotes and you will be fine:

sed -n -e "$FT_LINE1,${FT_LINE2}p"

See also:

codeforester
  • 39,467
  • 16
  • 112
  • 140
  • maybe you also can explain the one more thing. when I am using ft1=8 and ft2 = 15 its showed shifted result by 1 to the right, how to fix it? – Vasyl Kozhushko Jul 25 '17 at 18:40