user2231752
user2231752

Reputation: 11

using sed -n with variables

I am having a log file a.log and i need to extract a piece of information from it. To locate the start and end line numbers of the pattern i am using the following.

start=$(sed -n '/1112/=' file9 | head -1)
end=$(sed -n '/true/=' file9 | head -1)

i need to use the variables (start,end) in the following command:

sed -n '16q;12,15p' orig-data-file > new-file 

so that the above command appears something like:

sed -n '($end+1)q;$start,$end'p orig-data-file > new-file

I am unable to replace the line numbers with the variables. Please suggest the correct syntax.

Thanks, Rosy

Upvotes: 1

Views: 2162

Answers (2)

jaguarg78
jaguarg78

Reputation: 11

When I realized how to do it, I was looking for anyway to get line number into a file containing the requested info, and display the file from that line to EOF.

So, this was my way.

with

PATTERN="pattern"
INPUT_FILE="file1"
OUTPUT_FILE="file2"

line number of first match of $PATTERN into $INPUT_FILE can be retrieved with

LINE=`grep -n ${PATTERN} ${INPUT_FILE} | awk -F':' '{ print $1 }' | head -n 1`

and the outfile will be the text from that $LINE to EOF. This way:

sed -n ${LINE},\$p ${INPUT_FILE} > ${OUTPUT_FILE}
  • The point here, is the way how can variables be used with command sed -n:

first witout using variables

sed -n 'N,$p' <file name>

using variables

LINE=<N>; sed -n ${LINE},\$p <file name>

Upvotes: 1

suspectus
suspectus

Reputation: 17278

Remove the single quotes thus. Single quotes turn off the shell parsing of the string. You need shell parsing to do the variable string replacements.

sed -n '('$end'+1)q;'$start','$end''p orig-data-file > new-file

Upvotes: 0

Related Questions