سؤال

I want to remove all characters after specific char "/" in all result lines of cut command How may I do that using bash commands?

for example if cut -f2 file results :

John.Micheal/22
Erik.Conner/19
Damian.Lewis/40

I need this on output:

John.Micheal
Erik.Conner
Damian.Lewis
هل كانت مفيدة؟

المحلول

You can pipe it to another cut, using / as the field separator:

cut -f2 file | cut -f1 -d/

Or you could use sed to cut off everything beyond /:

cut -f2 file | sed 's?/.*??'

Or you could use a single awk with a custom field separator, assuming there are no / in the first field:

awk -F'[\t/]' '{print $2}' file

If there can be / in the first field then it's better to use the first two suggestions.

نصائح أخرى

Or use pure bash while loop to read line by line into a shell variable. One option:

cut -f2 file | while IFS=/ read -r a _; do echo "$a"; done

Another option:

cut -f2 file | while read -r a; do echo "${a%/*}"; done

First one uses IFS word splitting during read, another uses parameter expansion.

without knowing what you file looks like, it's better to pipe the result of cut -f2 file to another cut or awk or sed as suggested by @janos, or use @kastelian's method

since cut -f2 file gives you

John.Micheal/22
Erik.Conner/19
Damian.Lewis/40

I am guessing this is what your original file looks like

ab/c    John.Micheal/22 abc/23
de      Erik.Conner/df  abc
        Damian.Lewis/40 def/999

instead of cut and pipe the output to another command, you can get the result directly
to get the string between the first tab and the first / after tab

 sed  's@^[^\t]*[\t]\+\([^/]\+\)/.*@\1@' file

or if you have GNU sed

 sed -r 's@^[^\t]*[\t]+([^/]+)/.*@\1@' file

Just use awk for the whole thing:

awk -F'\t' '{split($2,a,"/"); print a[1]}' file

If there are no other "/"s in your first 2 fields then you can reduce to:

awk -F'[\t/]' '{print $2}' file
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top