Pergunta

Having some difficulty in getting a sed | grep pipe to work when using vars as numbers. In the string below the '3,5p' works fine, but when substituting the numbers for vars I get the error

sed: -e expression #1, char 4: extra characters after command

working=$(sed -n '3,5p' ${myFile} | grep -n "string" |cut -f1 -d: )

notWorking=$(sed -n '${LINESTART},${LINEEND}p' ${myFile} | grep -n "string" |cut -f1 -d: )

I would also be interested in any advice how I could change command so the line number returned is replaced with $string2 in the file myFile

thanks Art

Foi útil?

Solução

You need the variables to be expanded by sed. For that, you have to enclose the expression within double quotes:

sed -n  "${LINESTART},${LINEEND}p"  ${myFile} 
        ^                        ^

instead of

sed -n  '${LINESTART},${LINEEND}p'  ${myFile}

As you are checking for the line number in $myFile where string is found, it line is in between $LINESTART and $LINEEND, you can do:

awk 'NR>=start && NR<=end && /string/ {print NR}' start=$LINESTART end=$LINEEND ${myFile}

Suppose you want to replace a string just if it appears in specific lines. You can use this:

sed -i.bak "$LINESTART,$LINEEND s/FIND/REPLACE/' file
  • -i.bak makes a backup of the file and does an in-place edit: file will contain the modified file, while file.bak will be the backup.

Test

$ cat a
hello
this is
something
i want changed
end
but this is not to be changed

$ sed -i.bak '3,5 s/changed/NEW/' a
$ cat a
hello
this is
something
i want NEW      <---- "changed" got replaced
end
but this is not to be changed <---- this "changed" did not
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top