1

I'm trying to use sed to find matching string on a line in a file on nth match. I want to use expression to mach num and "anything" after on that line and replace it with num x.

example file:

START
num 1
num 1
num 1
num n
END
sed ':a;N;$!ba; s/num .*/num x/1' example 

outputs:

START
num x

sed ':a;N;$!ba; s/num 1/num x/1' example 

outputs:

START
num x
num 1
num 1
num n
END

Im tyring to use the .* expression to match anything after num and replace it with num x but my result leaves the end of the file out. Replacing the .* expression with the actual full string on that line gives the desired result, but it must be possible that there is "anything" following characters on that line.

1
  • 1
    It's unclear what your expected output should look like. Please edit your question to add it.
    – Kusalananda
    Commented Mar 27, 2020 at 15:35

2 Answers 2

1

Your regex was not exactly right.

$ sed ':a;N;$!ba; s/\nnum[^\n]*/\nnum x/4' file 
0

sed is the best tool for doing s/old/new on individual lines, for anything else just use awk;

$ awk -v n=4 '/num/ && ((++c) == n){$0="num x"} {print}' file
START
num 1
num 1
num 1
num x
END

You must log in to answer this question.

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