Search code examples
bashshellsedps

Removing part of a line? [bash]


I'm writing my own ps-command in bash, but i'm having some trouble getting cmdline. This is my code:

get_cmdline(){
if [ -f "/proc/$1/cmdline" ]; then
cat /proc/$1/cmdline | cut -d " " -f 1
else echo n/a
fi
}

But this is what i'm getting:

/opt/google/chrome/chrome-sandbox/opt/google/chrome/chrome--type=zygote

What is the easiest way to remove '--type=zygote'?

PS: I don't know command sed, so if used, I would greatly appreciate a detailed explanation

Thanks a lot


Solution

  • using awk:

    echo "/opt/google/chrome/chrome-sandbox/opt/google/chrome/chrome--type=zygote" | awk -F "--" '{print $1}'
    /opt/google/chrome/chrome-sandbox/opt/google/chrome/chrome
    

    awk will delimit the record on '--'. then i am printing field one only 1st field

    using sed:

    echo "/opt/google/chrome/chrome-sandbox/opt/google/chrome/chrome--type=zygote" | sed 's/--.*//g'
    /opt/google/chrome/chrome-sandbox/opt/google/chrome/chrome
    

    using pattern matching:

    a="/opt/google/chrome/chrome-sandbox/opt/google/chrome/chrome--type=zygote" 
    echo ${a%--*}
    /opt/google/chrome/chrome-sandbox/opt/google/chrome/chrome