Home > front end >  create an array like structure if doesn't exists in a file and add content to it in shell scrip
create an array like structure if doesn't exists in a file and add content to it in shell scrip

Time:01-12

I need to check if an array exists in a file and create it if doesn't exists and add content to it as explained below:

a.txt:

fs.m = [
 abc,
]

Suppose I need to add ‘xyz’ to the array like this:

fs.m = [
 xyz,
 abc,
]

If array doesn’t exists then after creating new array and adding ‘xyz’ to it would look like:

fs.m = [
 xyz,
]

bash script I am using to solve it: add_array_text.sh

#!/bin/bash

if grep -A1 -qE '^fs.m *= *\[' a.txt; then
    echo -e "xyz," >> a.txt
else
    echo -e 'fs.m = [' >> a.txt
    echo -e "xyz," >> a.txt
    echo -e "]" >> a.txt
fi

After execuing add_array_text.sh, a.txt:

fs.m = [
 abc,
]
xyz

This script works fine if array doesn't exists but doesn't as new content is aded after the array if array exists already.

With A1 I tried to get the file context after the match but not able to save it and use it.

Thanks for the help in Advance.

CodePudding user response:

If an array exists, you can do following (assuming file is not too large)


    new_element='xyz'
    cat a.txt | while read line; do
        echo $line >> b.txt
        if [[ $line =~ 'fs.m = [' ]]; then
            echo ${new_element}, >> b.txt
        fi
    done
    mv a.txt a_old.txt
    mv b.txt a.txt

CodePudding user response:

Finally I made it working with below script att_array_text.sh:

#!/bin/bash

if ! grep -q '^fs.m[[:space:]]*=[[:space:]]*\[' a.txt; then
    echo 'fs.m = [' >> a.txt
    echo "xyz," >> a.txt
    echo "]" >> a.txt
else
    sed -i 's/\(^fs.m[[:space:]]*=[[:space:]]*\[\)/\1'"\nxyz,"'/' a.txt
fi
  • Related