asdf
asdf

Reputation: 2441

Susbtitution in sed with spaces

I have the following variable in bash:

var1="this is ok"

and in a file I want fo make in all lines the subst:

_day 23. 45. 56. ...

to

this is ok_day 23. 45. 56. 

so I add var1 to the start of the line

I tried with this

sed -e "s/_/${var1}"_"/g" ${filename}

but i get errors

I do not know if this is because the spaces. I aslo chaged / to | on sed but nothing

any hints?

Thanks

Upvotes: 1

Views: 3142

Answers (5)

Einar Indridason
Einar Indridason

Reputation: 1

In this case enclose the "this is ok" with single quotes, not double quotes.

as in:

$ var1='this is ok'

Reason being the shell handles whitespace differently depending on the quotation marks used....

Upvotes: 0

mouviciel
mouviciel

Reputation: 67829

You don't need to use double quotes around _ and you should not add a global modifier:

sed -e "s/_/${var1}_/" "${filename}"

Whitespaces in $var1 should not be a problem. Whitespaces in $filename can be a problem.

Upvotes: 3

Alex Brown
Alex Brown

Reputation: 42872

var1="this is ok"; 
echo _day 23. 45. 56. | 
  sed "s/^/${var1}/"

outputs

this is ok_day 23. 45. 56.

Alternatively, use awk (no messing around with regexps, which aren't required)

echo _day 23. 45. 56. |
  awk '{print "'"$var1"' " $1}' < abc.txt

Upvotes: 0

ghostdog74
ghostdog74

Reputation: 342363

you can just use the shell

#!/bin/bash
var1="this is ok"
while read -r line
do
    case "$line" in
        _* ) line=${var1}$line;;
    esac
    echo $line
done <"file"

output

$ cat file
sldfj
_day 23. 45. 56.
alskjf

$ ./shell.sh
sldfj
this is ok_day 23. 45. 56.
alskjf

if you absolutely want to use sed,

sed -e "/^_/s/^/$var/" file

or with awk

awk -v var="$var" '/^_/{$0=var $0 }1'  file

Upvotes: 3

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798646

The subst pattern you gave will not put $var1 at the beginning of the line:

sed -e "s/^/$var1/g" "${filename}"

Upvotes: 1

Related Questions