简体   繁体   中英

Replace text between 2 strings in bash with result of ls

I want to create an automation for a deployment, the js/css are generated with a prefix and I want to import them in the php file between the tags

Expected Output

...
/*bashStart*/
drupal_add_css(drupal_get_path("module","myModule")."/styles/c91c6d11.main.css");
drupal_add_js(drupal_get_path("module","myModule")."/scripts/j91c6d11.main.js");
/*bashEnd*/
...

I used awk and got me here so far but I have a problem, it's generating

    ...
    /*bashStart*/
    drupal_add_css(drupal_get_path("module","myModule")."/styles/c91c6d11.main.css
");
    drupal_add_js(drupal_get_path("module","myModule")."/scripts/j91c6d11.main.js
");
    /*bashEnd*/
    ...

here is the awk script:

awk 'BEGIN {p=1}/Start/{print;printf("drupal_add_css(drupal_get_path(\"module\",\"myModule\").\"/styles/");system("ls styles");printf("\");\n");printf("drupal_add_js(drupal_get_path(\"module\",\"myModule\").\"/scripts/");system("ls scripts");printf("\");\n");p=0}/Finish/{p=1} p' myModule.module > tmp;

Using ls within awk isn't very nice - I think you can do this entirely in the shell:

#!/bin/bash

p=1
while read -r line; do
    [[ $line = '/*bashEnd*/' ]] && p=1
    (( p )) && echo "$line"
    if [[ $line = '/*bashStart*/' ]]; then
        p=0
        for style in styles/*; do
            echo 'drupal_add_css(drupal_get_path("module","myModule")."/styles/'"$style"'");'
        done
        for script in scripts/*; do
            echo 'drupal_add_js(drupal_get_path("module","myModule")."/scripts/'"$script"'");'
        done
    fi
done < file.php > output.php

Loop through the input file until you reach the "bashStart" line, then add the lines you want. Output goes to a file output.php which you can check before overwriting the original file. If you're feeling confident you can add && mv output.php file.php to the done line, to overwrite the original file.

The flag p controls which lines are printed. It is set to 0 when the "bashStart" line is reached and back to 1 when the bashEnd line is reached, so lines between the two are replaced.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM