2

The codeline below adds two different fixed-strings to beginning, and end of a line.

sed -i 's/.*/somefixedtext,&,someotherfixedtext/' ${f}

somefixedtext,20,30,10,50,someotherfixedtext

I want to enhance the output by using a variable, to give me below, instead of whats above;

HELLO,somefixedtext,20,30,10,50,someotherfixedtext

Tried some variations but all failed;

VARIABLE="HELLO"
sed -i 's/.*/"$VARIABLE,somefixedtext,&,someotherfixedtext/' ${f}

How can I incorporate a string variable to beginning of the line, combined with a fixedstring, in Sed ?

1 Answer 1

4

Sed is a poor choice if the replacement string is from a variable, because it treats the variable as a sed command and not as literal string, so it will break if the variable contains special characters like / or & or similar.

Awk is better suited for this task, for example like:

$ cat file
20,30,10,50

$ var=hello

$ awk -F, -v prefix="$var" -v OFS=, '{print prefix, "sometext", $0, "somethingelse"}' file
hello,sometext,20,30,10,50,somethingelse

For inplace modification you will need a recent version of GNU awk, and the -i inplace arguments.

For what it's worth, the command would appear to work if you double quoted the variable, outside the single quotes, but it would be a bit buggy:

VARIABLE="HELLO"
sed -i 's/.*/'"$VARIABLE"',somefixedtext,&,someotherfixedtext/' ${f}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much, the Sed version works very well. These two single quotes ate my 2 hours :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.