0

In sed, we use double quotes to read environment variable indicated by a dollar sign, what should i do if I want to use the dollar sign for end-of-line pattern at the same time?

Here is example of my command (not working),

cat inputfile | xargs -n4 sh -c 'sed -ne "$1,$2p" bigfile|sed -e "$s/$/\n+--$3-----+/" > $0.outputfile' 

I pipe the content of a input file (containing the output filename, target line number (start and end), and some tags to add to each file) to xargs which break the big file into smaller files. Example of input file:

dataA
59
88
sometagA
dataB
91
236
sometagB
....

In the second sed command: sed -e "$s/$/\n+--$3-----+/", $3 is environment variable from xargs, and i want to use the other $s and $ to target end-of-file and end-of-line pattern respectively, as i intent to insert some tags to each output file. I cannot use single and double quote at the same time as the outter xargs already used single quote.

glennsl
  • 28,186
  • 12
  • 57
  • 75
once
  • 1,369
  • 4
  • 22
  • 32

2 Answers2

2

Use backslash to escape a dollar sign from the shell.

xargs -n4 sh -c 'sed -ne "$1,$2p" bigfile |
    sed -e "\$s/\$/\n+--$3-----+/" > "$0".outputfile' <inputfile

You only pass four arguments and they are numbered from zero, so I guess you mean $3, not $4.

Notice also how to avoid the useless cat.

The two sed scripts could probably be merged into something like

sed -n "$1,$2!d;$2{;s/\$/+--$3-----+/p;q;}p"
tripleee
  • 175,061
  • 34
  • 275
  • 318
1

escape it from bash shell to have an end anchor

sed -ne "$1,$2p" bigfile|sed -e "$s/\$/\n+--$3-----+/"

escape it once more from sed to have a literal dollar sign e.g;

sed -ne "$1,$2p" bigfile|sed -e "$s/\$/\n+--$3-----+/| sed 's/.*/& pays \\$99/'