0

I am attempting to write a very simple one liner SED command that does not employ bash conditions.

For a SED command that does something similar but instead appends to the end of the file, I use the following:

sed -n -e '/.*MYLINE.*/!p' -e '$aVAR=MYLINE' -i /path/to/file

But this time, the position of inserted line is critical, so it should be right after specific string. I attempted the following:

sed -n -e '/.*MYLINE.*/!p' -e t -i '/^ANOTHER_PATTERN.*/aVAR=MYLINE' /path/to/file

so I can turn the /path/to/file from this one

...
ANOTHER_PATTERN=SOMETHING
...

or this one

...
ANOTHER_PATTERN=SOMETHING
VAR=OTHERS MYLINE
...

to produce this

...
ANOTHER_PATTERN=SOMETHING
VAR=MYLINE
...

however, it does not produce the expected outcome. I tried googling but to no avail.

How to correctly perform search for pattern if exist then replace the whole line else insert a new line after a another pattern using SED?

2
  • I'm not sure about the intention of your t command. This jump on a successful substitute, but you don't even have an s command.
    – Philippos
    Jun 7, 2021 at 9:56
  • .indeed, I dont know.
    – Jones G
    Jun 8, 2021 at 4:15

2 Answers 2

4
sed -e '/MYLINE/d' -e '/^ANOTHER_PATTERN/a\
VAR=MYLINE' file

This deletes the line if it contains the pattern MYLINE and appends line VAR=MYLINE to a line starting with pattern ANOTHER_PATTERN. Add option -i to edit the file in-place if your sed implementation supports it.

4
  • I will test this, where to add the -i?
    – Jones G
    Jun 5, 2021 at 15:52
  • 1
    I'd add it as the first option.
    – Freddy
    Jun 5, 2021 at 15:55
  • The only difference of that from the append to end is the d vs !p on the first command, can you please explain what does the d do?
    – Jones G
    Jun 5, 2021 at 15:56
  • 1
    The !p is a negated print (not print), the d deletes the pattern space. You don't need -n in combination with d.
    – Freddy
    Jun 5, 2021 at 16:04
1

Using awk:

awk '/MYLINE/{next}; 
/^ANOTHER_PATTERN/{$0 = $0 ORS "VAR=MYLINE";}1' input

With expression /MYLINE/{next} no further action is taken. This, in effect, prevents printing of the record when awk's 1 idiom for the printing is used. If another pattern is found, current input record($0) is changed to $0 followed by newline then followed by VAR=MYLINE.

1
  • 1
    Tnx for an alternative solution. I wish to avoid the if-statement cause its hard to read in one line. I upvoted anyway.
    – Jones G
    Jun 5, 2021 at 16:31

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .