DroidOS
DroidOS

Reputation: 8900

Shell script substring till space

I'd be most obliged to anyone who might be able to tell me how I can extract all characters up to the first space or tab character after having tested that what follows the space/tab is another specified substring? For example a file containing

php server-side
asp server-side
css client-side
html client-side
golang server-side

when read line-by-line could be used to generate the string

php asp golang

i.e. with the lines ending client-side dropped out altogether and the lines containing server-side truncated at the space.

Upvotes: 8

Views: 18614

Answers (5)

krad
krad

Reputation: 51

grep "server-side" FILE_NAME | awk '{print $1}'

Explanation: grep "server-side" FILE_NAME can filter out those client side entries. Then awk '{print $1}' can print only the first row of the text.

Upvotes: 5

tripleee
tripleee

Reputation: 189679

If your intent is to loop over the tokens in a shell loop anyway, the shell has whitespace splitting built in.

sep=''
while read -r lang feat; do
    case $feat in "client-side" ) continue;; esac
    printf '%s%s' "$sep" "$lang"   # replace this with something actually useful?
    sep=' '
done <<____HERE
    php server-side
    asp server-side
    css client-side
    html client-side
    golang server-side
____HERE

Upvotes: 3

Avinash Raj
Avinash Raj

Reputation: 174786

Through sed,

$ sed -n 's/[[:space:]]\+server-side$//p' file
php
asp
golang

Pass the output to tr command is you want a folded output.

sed -n 's/[[:spacee$//p' ri | tr '\n' ' '

Upvotes: 2

schtever
schtever

Reputation: 3250

grep server-side foo.txt | cut -d' ' -f1 | paste -s -

Upvotes: 1

Arnab Nandy
Arnab Nandy

Reputation: 6712

This command will do the trick,

grep "server-side" filename|cut -d ' ' -f1|tr '\n' ' '

Explanation as follows;

grep "server-side" filename

It will capture only lines matched with the string server-side.

cut -d ' ' -f1

cut commmand will cut first column of the table by delimiter space.

tr '\n' ' '

tr command will make all new line character replaced with a space.

Output will be exactly what OP mentioned in question(requirement):

php asp golang

Upvotes: 17

Related Questions