1748089 Members
4919 Online
108758 Solutions
New Discussion юеВ

need remove second field

 
SOLVED
Go to solution
Allanm
Super Advisor

need remove second field

Hi!

I have a file which looks like this -

host packagename -install -app Appname

packagename is of this pattern -

Appname-20110304-131123-hexanumbers

1)The list is pretty long and I want to remove the packagenames from all entries. How can I remove the second entry from each row(delete the packagename)?

2)Also it would be helpful if I can know how to remove the entries after Appname in the packagename.(so instead of Appname-20110304-131123-hexanumbers I can get Appname in the second field)?

Thanks,
allan.
5 REPLIES 5
Allanm
Super Advisor

Re: need remove second field

3) it would nice to know if I can add a text in the second field instead of the packagename.
(replace Appname-20110304-131123-hexanumbers with the word text)?
Steven Schweda
Honored Contributor
Solution

Re: need remove second field

> How can I [...]

Write a shell script?

man sed

alp$ echo 'host Appname-20110304-131123-hexanumbers -install -app Appname' | \
sed -e 's/ [^ ]* / /'
host -install -app Appname

alp$ echo 'host Appname-20110304-131123-hexanumbers -install -app Appname' | \
sed -e 's/-.*$//'
host Appname

alp$ echo 'host Appname-20110304-131123-hexanumbers -install -app Appname' | \
sed -e 's/ [^ ]* / text /'
host text -install -app Appname


It's not easy to do the whole job without
knowing from where "text" will be coming.

/ [^ ]* /
means a space, any number ("*") of non-space
characters ("[^ ]"), and a space.

/-.*$/
means a "-", any number ("*") of any
characters ("."), and the end of the line
("$").


man sed
Dennis Handly
Acclaimed Contributor

Re: need remove second field

>1) How can I remove the second entry from each row (delete the packagename)?

awk '{print $1, $3, $4, $5}' file

>2) Also it would be helpful if I can know how to remove the entries after Appname in the packagename. (so I can get Appname in the second field)?

Is this Appname the same as field 5?
awk '{print $1, $5, $3, $4, $5}' file

Otherwise:
awk '
{
dash = index($2 , "-") # find "-"
if (dash == 0)
app = $2
else
app = substr($2, 1, dash-1)
print $1, app, $3, $4, $5
}' file
Dennis Handly
Acclaimed Contributor

Re: need remove second field

>3) it would nice to know if I can add text in the second field instead of the packagename.
awk -v text="$text_variable" '{print $1, text, $3, $4, $5}' file
James R. Ferguson
Acclaimed Contributor

Re: need remove second field

Hi Allan:

>2) Also it would be helpful if I can know how to remove the entries after Appname in the packagename. (so I can get Appname in the second field)?

You can let 'awk' split subfields on a different deliminter, too:

# X="host Appname-20110304-131123-hexanumbers -install -app Appname"

# echo${X}|awk '{if (split($2,app,"-") > 0) {print $1,app[1],$3,$4,$5} else {print}}'
host Appname -install -app Appname

As always, TMTOWTDI

Regards!

...JRF...