简体   繁体   中英

linux bash script cut string after first occurance of a character

I'm trying to get the names of all processes in "screen -list"

Unfortunately I already fail at the loop, because

for PLINE in `screen -list | grep 'tached)'`; do
    echo "$PLINE"
done

outputs

3698.processname
(16/08/12
12:59:37)
(Detached)

but my expected output was

    3698.processname    (16/08/12 12:59:37)    (Detached)

like when directly type screen -list | grep 'tached)' screen -list | grep 'tached)' into the console.

What I was trying to do if this loop would've worked, is using cut -d '.' -f 2 cut -d '.' -f 2 and then cutting off the result string after the first whitespace found. ( Which Im also not quite sure how to do yet, all I know is something with %' ' )

So, I think it's pretty obvious that I have not much of a clue in bash script, thus I'm open for more elegant suggestions to do what Im trying to do.

(Edit) Solution:

for PLINE in `screen -list | grep 'tached)' | awk -F '[ \t\n\v\r.]' '{print $3}'`; do
    echo $PLINE
done
$ awk -F '[ \t\n\v\r.]' '{print $2}' <<< $'3698.processname    (16/08/12 12:59:37)    (Detached)'
processname

But there's no need to pipe grep into awk; just have awk match the regex itself.

If all you want is the name, then let's just grab that instead of the whole line.

# screen -list
There are screens on:
    85384.ttyv3.filer0  (Attached)
    85617.another   (Detached)
    57491.pts-0.filer0  (Dead ???)
Remove dead screens with 'screen -wipe'.
2 Sockets in /tmp/screens/S-root.

# screen -list | awk '/ched/{split($1,a,".");print a[2]}'
ttyv3 another
#   

You want it in a variable? A for loop?

# read names <<<$(screen -list | awk '/ched/{split($1,a,".");print a[2]}')
# echo $names
ttyv3 another
# for name in $names; do echo "name=$name"; done
name=ttyv3
name=another
#

Of course, you can avoid most of this noise with pure bash:

screen -list | while read name status; do
  if [[ $status =~ ched ]]; then
    echo "${name#*.}"
  fi
done

This is probably your best solution, as it doesn't rely on any external tools like awk or grep. It'll be more portable, faster and less resource intensive.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM