4

Sample File

a.b.gg3d 0000000001 0000000001 y
a.b.112a 0000000000 0000000001 y
a.b.gg3s 0000000001 0000000001 y
a.b.1111 0000000000 0000000001 m

I have a file that includes about three thousand unique lines, similar to the sample above. I want to use sed to remove the "xxxxxxxxxx xxxxxxxxxx" numbers from each line. Using the sample above, I would like the sed script to produce the following output:

a.b.gg3d y
a.b.112a y
a.b.gg3s y
a.b.1111 m

How can I accomplish this? Is there a string of commands to tell sed something like "delete all numbers after the first whitespace, but leave the last character"?

4

Given this input, you want to keep the first and last fields. Pretty simple with awk:

awk '{print $1, $NF}' filename

Using sed, this will replace all space delimited digit-only words:

sed ':a; s/ [[:digit:]]\+ / /; ta'
  • I understand that the s means substitute and the forward slashes are delimiters, but what do the following commands mean? :a; \+ and ; ta – user46865 Sep 10 '13 at 20:19
  • :a is a label, ta means "go to a": in short, it is a loop – enzotib Sep 10 '13 at 20:31
  • 1
    And sed 's/ [[:digit:] ]\+ / /' can do it the same – enzotib Sep 10 '13 at 20:34
  • I was thinking along the lines of enzotib, but went with sed 's/[[:space:]][[:digit:]]\+//g' which removes one or more numbers [[:digit:]]\+ proceeded by whitespace (tabs, spaces) [:space:], and also specified /g to the options, to do it for all occurrences (and not just the first) – Drav Sloan Sep 10 '13 at 20:41
  • The reason I searched for the trailing space in a loop was to avoid matching " 123abc" -- i.e. to ensure that the word was composed only with digits. – glenn jackman Sep 11 '13 at 12:41
1

Another solution only using cut, that will print the first and fourth column:

cut -d' ' -f1,4 < samplefile.txt
  • 1
    By far the most appropriate solution IMO. If all that needs to be done is to remove columns that are well defined by their delimiters, than cut is the right tool for the job. However, the -1 should be just 1 as there are no columns to the left of the first one. – Kusalananda Feb 16 '17 at 8:52
0
sed -e 's/[ ].*[ ]/ /' yourfile

This looks at the leftmost space and up till the rightmost space and replaces this with a single space. IOW, first & last fields are retained.

Assuming that there are no leading &/or trailing spaces. There are no TABs.

Otherwise, we can always do the following:

SPC=`echo 'x' | tr 'x' '\040'`
TAB=`echo 'x' | tr 'x' '\011'`
WS="[$TAB$SPC]"
sed -e "s/^$WS*//;s/${WS}\$//;s/${WS}.*${WS}/${SPC}/" < yourfile
0
$ echo "a.b.gg3d 0000000001 0000000001 y" |sed -r 's/[ ]+[0-9]+//g'
a.b.gg3d y

-r regex mode

You're searching for one or more spaces, followed by one or more numbers of any in range 0-9. Technically this is matching twice, leaving your third space in between a.b.gg3d and y.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy