bash to get required lines from file using sed/awk

File content as below:

Text1:
    text_1: Text1 text_1
    text_2:
    - text
    - file1:\
    - file2:\
Text2:
    text_1: Text2 text_1
    text_2:
    - text
    - file3:\
Text3:
    etc

Output:
print "file:" entries for given Textn.
Any idea how to achieve this using sed/awk commands in Linux.

Example: test.txt file contents as below:

$ cat test.txt 
Text1:
    text_1: Text1 text_1
    text_2:
    - text
    - file1:\
    - file2:\
Text2:
    text_1: Text2 text1
    text_2:
    - text
    - file3:\
Text3:
    etc

tried below grep command as suggested and it prints all "file:" entries in test.txt file. For "Text1:" match all I need is file1: and file2: as output and For "Text2:" match file3: only.

Asked By: Rang's

||

Using yq on the newly updated YAML file you can select the file values like this

yq '.Text1.text_2[] | select(. == "file*")' file.yaml

Output

file1:\
file2:\

If you want to be able to pick out the different TextN values you can do something like this to pass in the appropriate key value

for key in Text1 Text2
do
    printf 'Key %s:n' "$key"
    yqText="$key" yq 'eval("." + env(yqText) + ".text_2[]") | select(. == "file*")' file.yaml |
        while IFS= read -r val
        do
            printf 'Value: %sn' "$val"
        done
    echo
done

If you don’t have yq installed you can either install it yourself from the Github repository at https://github.com/mikefarah/yq, or if it’s for use in a managed environment then ask your Change Board.

Answered By: roaima
Categories: Answers Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.