Difference between revisions of "variable usage in sed commands"

From thelinuxwiki
Jump to: navigation, search
(Created page with " Example print only lines 2 through 4 of file $ '''printf "one\ntwo\nthree\nfour\nfive\n" | sed -n '2,4p'''' <br>two <br>three <br>four same using variables START=2 END=4 ...")
 
 
(3 intermediate revisions by one user not shown)
Line 11: Line 11:
 
same using variables
 
same using variables
  
START=2
+
$ '''START=2'''
END=4
+
<br>$ '''END=4'''
 
+
<br>$ '''printf "one\ntwo\nthree\nfour\nfive\n" | sed -n "${START},${END}p"'''
$ '''printf "one\ntwo\nthree\nfour\nfive\n" | sed -n "${START},${END}p"'''
+
 
<br>two
 
<br>two
 
<br>three
 
<br>three
Line 22: Line 21:
  
 
$ '''printf "one\ntwo\nthree\nfour\nfive\n" | sed -n "$START,$ENDp"'''
 
$ '''printf "one\ntwo\nthree\nfour\nfive\n" | sed -n "$START,$ENDp"'''
sed: -e expression #1, char 2: unexpected `,'
+
<br>sed: -e expression #1, char 2: unexpected `,'
  
 
solution is to include the curly braces around the variable names
 
solution is to include the curly braces around the variable names

Latest revision as of 20:12, 24 January 2018

Example

print only lines 2 through 4 of file

$ printf "one\ntwo\nthree\nfour\nfive\n" | sed -n '2,4p'
two
three
four

same using variables

$ START=2
$ END=4
$ printf "one\ntwo\nthree\nfour\nfive\n" | sed -n "${START},${END}p"
two
three
four

Examples that FAIL...

$ printf "one\ntwo\nthree\nfour\nfive\n" | sed -n "$START,$ENDp"
sed: -e expression #1, char 2: unexpected `,'

solution is to include the curly braces around the variable names


$ printf "one\ntwo\nthree\nfour\nfive\n" | sed -n '${START},${END}p'
sed: -e expression #1, char 3: unknown command: `S'

solution is to use double quotes in the sed commands so the variables are expanded