1

I am attempting to remove strings from file1.txt as part of a bash script.

For example, the file contains:

@some_group1 = take.me bake.shake test.test push.pull
@some_group2 = test.test take.me bake.shake push.pull
@some_group3 = take.me bake.shake push.pull test.test

The output I desire is:

@some_group1 = take.me bake.shake push.pull
@some_group2 = take.me bake.shake push.pull
@some_group3 = take.me bake.shake push.pull

I have attempted using the sed command but have no luck getting it to work.

sed -i 's/\[?]\$username\[?]\/  /g' file1.txt

What would be the best way to accomplish this task?

  • sed 's/ test.test//' /path/to/file? – DopeGhoti Mar 19 '18 at 22:26
2

sed solution:

username="test.test"
sed "s/ *$username */ /" file

The output:

@some_group1 = take.me bake.shake push.pull
@some_group2 = take.me bake.shake push.pull
@some_group3 = take.me bake.shake push.pull 
| improve this answer | |
0

To use single quotes and insert a variable name do like this:

sed 's/ '"$username"'//' file1.txt

It's not very pretty, but could be useful sometime. Regardless of using single quotes or double quotes directly, there's a sneaky underlying issue with the code. If the variable contains a '/', sed will treat it as part of the 's' command, which means there will be 4 slashes and you'll get a syntax error like:

sed: bla bla bla: unknown option to `s'   #good luck debugging that :)

To deal with this, I usually choose another syntax delimiter character, one that I know is least likely to appear in my variable. For example, the new command would become:

sed 's# '"$username"'##' file1.txt
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.