Search code examples
bashawksudo

awk command print the file content while executing with sudo bash in ub20.04


I have a .txt file containing following:

Depends: abc
Depends: def
Depends: ghi

I am using ub20.04

While executing following command:

cat demo.txt | awk -F'Depends:' 'NF > 1 {print $2}'

I get output as follows:

abc
def
ghi

But while running:

sudo -s bash -c "cat demo.txt | awk -F'Depends:' 'NF > 1 {print $2}'"

awk command is not working(it is just print the content of the file), output:

Depends: abc
Depends: def
Depends: ghi

Solution

  • awk command is not working(it is just print the content of the file), output:

    It is due to the presence of $2 inside the double quotes which is expanded by shell and evaluating to an empty string and then print $2 is becoming just print, which will obvious print full line.

    sudo awk -F 'Depends:' 'NF > 1 {print $2}' demo.txt
    

    Or better use sed:

    sudo sed 's/^Depends: //' demo.txt
    

    Note that cat is totally unnecessary as both awk and sed can directly operate on a file.