Search code examples
bashsedcat

Why I get empty file after sed -e?


given the following file file:

my name is: @NAME@

I ran this script:

name="Alin"
full_file="$(mktemp)"
cat file | \
    sed -e "s:@NAME@:${name}:g" | \
    >> "${full_file}"

cat "${full_file}"

but i get empty file (the ${full_file}) and i don't understand why..
I expectes to see this file as result:

my name is: Alin

What I missing here?


Solution

  • In your code, you redirect nothing to the new temporary file since the >> appears after the pipe.

    You need to remove the pipe after the sed command:

    name="Alin"
    full_file="$(mktemp)"
    cat file | \
        sed -e "s:@NAME@:${name}:g" \
        >> "${full_file}"
    
    cat "${full_file}"
    

    Or, simply put the >> "${full_file}" on the sed line:

    name="Alin"
    full_file="$(mktemp)"
    cat file | \
        sed -e "s:@NAME@:${name}:g" >> "${full_file}"
    
    cat "${full_file}"
    

    Or, since there is no point using cat pipe to sed here (mind that you can always pass the file name directly to the sed command):

    name="Alin"
    full_file="$(mktemp)"
    sed -e "s:@NAME@:${name}:g" file >> "${full_file}"
    cat "${full_file}"