File editing using builtin commands

I have a requirement to update a file on a Linux box and as I am performing a number of other updates using ansible, I’m hoping to use the same methodology. However… I can’t work out if what I’m trying to do is possible.

The file format is similar to:

<numerous lines of code>
# arrays
for x in \
    a \
    b \
    c
do
    ...
done

# integers
for x in \
    d \
    e \
    f
do
    ...
done

# strings
for x in \
    g \
    h \
    i
do
    ...
done

What I require is:

  • after: ‘^# integer’
  • before: ‘^do’
  • regex: ‘$’
  • replace: ’ \’

and:

  • after: ‘^# integer’
  • insertbefore: ‘^do’
  • line: ’ j’

This would result in:

<numerous lines of code>
# arrays
for x in \
    a \
    b \
    c
do
    ...
done

# integers
for x in \
    d \
    e \
    f \
    j
do
    ...
done

# strings
for x in \
    g \
    h \
    i
do
    ...
done

Is anything like this possible? At the moment my solution is to run the “ex” command with input from a command file. This works but isn’t self-contained.

Thanks.

Mu. By which I mean, if you want to solve the problem in an Ansible way, you’ll need to change the nature, the context, of the problem. Otherwise, your ex command file is going to be at least as elegant as any pure Ansible solution you might come up with.

What comes to mind is that you have three arrays, currently containing [a b c], [d e f], and [g h i]. That’s data, not code. Separate your data from code, and manage the data through Ansible. Template out the data into three files that your shell script (I mean, it looks like a shell script to me) can ingest with

mapfile -t arrays < arrays.lst
mapfile -t integers < integers.lst
mapfile -t strings < strings.lst

Then your loops become

for x in "${arrays[@]}"
do
    …
done

But this requires you to take ownership of the data, and thus changes the nature and context of the problem. But the solution changes from being, frankly, ugly regardless of the tool(s) employed to something quite straightforward to address with Ansible.

If this or some other change along those lines is not an option, then congratulations on your ex command file solution. I don’t think you’ll do better.

1 Like