Skip to content
Advertisement

How to insert char in mathed lines in a file

For example, I have a file with the content:

{

  a : "apple"

  b : "orange"

}

{

  a : "meat"

}

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

{

  a : "apple_1"

  b : "orange"

}

{

  a : "meat_1"

}

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:

awk '$1=="a:" || ($1=="a" && $2==":") {sub(/"$/,"_1"",$0)}1' file

(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:

$ awk '$1=="a:" || ($1=="a" && $2==":") {sub(/"$/,"_1"",$0)}1' file
{

  a : "apple_1"

  b : "orange"

}

{

  a : "meat_1"

}

Using sed

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

sed '/^s*as:/s/"$/_1"/' file

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

Advertisement