Search code examples
bashshellshxargs

Split file content strings by dash using xargs


I need to read a file and split every line into a domain and a application string

domain.com-backend
domain.com-frontend

For each line I need to call a docker build command (echo just to see the command):

cat $FILE | grep '-' | xargs -I {} echo docker build -t {full} -f apps/{domain}/{application}/Dockerfile .

So in the example I would expect the output

docker build -t domain.com-backend -f apps/domain.com/backend/Dockerfile .
docker build -t domain.com-frontend -f apps/domain.com/frontend/Dockerfile .

Solution

  • You can do it with this loop:

    while read -r x; do
        echo docker build -t "$x" -f "apps/${x/-/\/}/Dockerfile" .
    done < "$FILE"
    

    Remove echo after testing.

    See more for bash parameter expansion


    In case you want to first filter the file, e.g. there are more lines into there and you want first to grep "-" like in your example, you could use this syntax (bash only):

    while read -r x; do
        echo docker build -t "$x" -f "apps/${x/-/\/}/Dockerfile" .
    done < <(grep "-" "$FILE")