greg
greg

Reputation: 47

Using sed to add character in a line which contains TWO specific Strings

I want to do something like this:

sed "/^[^+]/ s/\(.*$1|$2.*$\)/+\ \1/" -i file

where 2 specific String Parameters are being checked in a file and in those lines where BOTH parameters ($1 | $2) occur, a + is added at the beginning of the line if there was no + before.

Tried different variations so far and ending up either checking both but then sed'ing every line that contains 1 of the 2 Strings or some errors. Thankful for any clarifications regarding slash and backslash escaping (respectively single/double quotes) i guess thats where my problem lies.

Edit: Wished outcome: (Folder containing bunch of text files one of which has the following 2 lines)

sudo bash MyScript.sh 01234567 Wanted

Before:

Some Random Text And A Number 01234567 and i'm Wanted.
Another Random Text with Diff Number 09812387 and i'm still Wanted.

Expected:

+ Some Random Text And A Number 01234567 and i'm Wanted.
Another Random Text with Diff Number 09812387 and i'm still Wanted. 

Upvotes: 3

Views: 698

Answers (1)

Benjamin W.
Benjamin W.

Reputation: 52132

For an input file that looks as follows:

$ cat infile
Some Random Text And A Number 01234567 and i'm Wanted.
Another Random Text with Diff Number 09812387 and i'm still Wanted.

and setting $1 and $2 to 01234567 and Wanted (in a script, these are just the first two positional parameters and don't have to be set):

$ set -- 01234567 Wanted

the following command would work:

$ sed '/^+/b; /'"$1"'/!b; /'"$2"'/s/^/+ /' infile
+ Some Random Text And A Number 01234567 and i'm Wanted.
Another Random Text with Diff Number 09812387 and i'm still Wanted.

This is how it works:

sed '
    /^+/b           # Skip if line starts with "+"
    /'"$1"'/!b      # Skip if line doesn't contain first parameter
    /'"$2"'/s/^/+ / # Prepend "+ " if second parameter is matched
' infile

b is the "branch" command; when used on its own (as opposed to with a label to jump to), it skips all commands.

The first two commands skip lines that start with + or that don' t contain the first parameter; if we're on the line with the s command, we already know that the current line doesn't start with + and contains the first parameter. If it contains the second parameter, we prepend + .

For quoting, I have single quoted the whole command except for where the parameters are included:

'single quoted'"$parameter"'single quoted'

so I don't have to escape anything unusual. This assumes that the variable in the double quoted part doesn't contain any metacharacters that might confuse sed.

Upvotes: 5

Related Questions