Although your question specifies "incrementing" (to add to an existing number, often by 1), the impression I get from reading your other comments is that you would really like to iterate through the clients in a file and read the number after "client" in one row, and then make the seat_num in the following row equal to the same number.
If that is the case, then the following sed command works for me, where test has the same contents as in the question. (I'm sure there are plenty of other ways to do it):
sed 'H;1h;$!d;x; s/client\([0-9]*\)\(\n[^\n]*\)seat_num=""/client\1\2seat_num="\1"/g' <<< cat test
This starts with a magic string from @Wiktor Stribizew's answer to this SO question: "(H;1h;$!d;x;
slurps the file into memory)". Reading the man page, I think it is copying the line of pattern read from the input into a "Hold space", then deleting the pattern and reading another line of pattern from the input until the input is ended, then swapping the "Hold space" back to the "Pattern space" ready to run the following substitution. However, I'm still not clear on the details, so I would be happy to be corrected.
In the substitution, we look for client
followed by 0 or more digits ([0-9]*
), and we use escaped parentheses \(
and \)
to remember the digits. Then we look for a newline followed by 0 or more not-newlines (so that we read only up to the next seat_num
), followed by the next seat_num=""
- again using escaped parentheses to remember what came before the seat_num=
.
We replace all of this with the original client
text and the remembered number (\1
uses the first remembered parameter) followed by the second remembered parameter, then the original seat_num="
text and a repeat of the first remembered parameter (the digit(s) after client
) and the final "
. As the pattern now contains the whole file, we use the g
command to do this substitution globally.
seat_num
intest
file? If it is not a number, it cannot be incremented. – sakkke Feb 18 '22 at 08:18seat_num=""
isn't a number – Chris Davies Feb 18 '22 at 09:11