[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: Editing Problem with bash script and sed



On Tue, Nov 14, 2017 at 07:21:55PM +0100, Thomas Schmitt wrote:
>   ls -d * | grep "$1" | while read filename

Eww.  No.  That code is broken in multiple ways.

>                   n=$(echo "$fname" | sed -e s/"$1"//)
> 
> Regrettably i found no way to make this safe against newlines in filenames.
> I'd do it in C language if such names were to be expected.

Well, the whole thing is a shambles.  Just use rename(1) which is
designed for this.

  rename 's/Badstring//' *Badstring*

The problems with using sed for this are numerous.  There's no way to
tell sed that the string you're passing should be treated as an argument
to a command.  All you can do is inject the user input directly into a
sed command.  This means that if the user input contains any characters
that sed uses as syntax, you lose.

If you had to do this on a legacy Unix system without perl, then see
<http://mywiki.wooledge.org/BashFAQ/030>


Reply to: