Skip to content
Advertisement

How to insert char in mathed lines in a file

For example, I have a file with the content:

JavaScript

I want to add “_1” in all the lines with “a : “, and get the result as:

JavaScript

Are there any ways by bash commands

Advertisement

Answer

Your spacing is unclear, whether you have "a : ..." or "a: ...". You also have what appears similar to json, and if so, you need to use a json-aware utility to ensure the result is validated as valid json.

If however, it’s just text, then awk can handle either case ("a : ..." or "a: ...") for you by checking if the first field (or first and second in the case of "a : ...") match your a: prefix. You then simply append _1 to the end of the line to preserve leading spaces using the sub function on the entire line (e.g. $0). In all cases the line is output, either unchanged or with _1 appended if your prefix is met.

You can do that with:

JavaScript

(note: you can remove whatever side of the || isn’t needed)

You can review the user of the sub function at GNU awk – String-Manipulation Functions

Example Use/Output

With your input file in file, the following results:

JavaScript

Using sed

You can also accomplish the same thing with sed (which may be slightly more efficient in this case) using:

JavaScript

Look things over and let me know if you have questions.

Advertisement