Reputation: 2441
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
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
Reputation: 67829
You don't need to use double quotes around _
and you should not add a g
lobal modifier:
sed -e "s/_/${var1}_/" "${filename}"
Whitespaces in $var1
should not be a problem. Whitespaces in $filename
can be a problem.
Upvotes: 3
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
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
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