3

Given this data

34 foo
34 bar
34 qux
62 foo1
62 qux
78 qux 

I want to replace the string at 2nd column into "" if it is "qux". Resulting:

34 foo
34 bar
34 
62 foo1
62 
78  

How do you do that with sed? In particular the data is very big with ~10^7 lines

2
  • Hey, is it space delimited, or whitespace delimited (spaces+tabs)?
    – guns
    Apr 2, 2009 at 2:47
  • Well, POSIX sed can't use '\t' to match tabs; you have to use literal tabs. gsed can, but awk will definitely match tabs with \t
    – guns
    Apr 2, 2009 at 2:51

3 Answers 3

15

I wouldn't actually do it with sed since that's not the best tool for the job. The awk tool is my tool of choice whenever somebody mentions columns.

cat file | awk '$2 == "qux" { print $1 } $2 != "qux" { print $0 }'

or the simplest form:

cat file | awk '{ if ($2 == "qux") {$2 = ""}; print }'

If you must use sed:

cat file | sed 's/  *qux *$//'

making sure that you use the correct white space (the above uses only spaces).

2
  • @Pax: thanks for the reply. BUt yours approach with awk give this instead: 34 bar 34 34 qux 62 foo1 62 62 qux 78 78 qux
    – neversaint
    Apr 2, 2009 at 2:44
  • Try again. I had a $s instead of $2.
    – paxdiablo
    Apr 2, 2009 at 2:45
3

No trailing spaces:

sed 's/qux$//' < file

If it must be in the second column (of potentially more than three columns):

sed 's/\([0-9][  ]*\)qux\(.*\)/\1\2/'

(Note that there is a literal tab and space; sed doesn't match tabs with '\t';

But awk is better for tabular data:

awk '{ if ($2 == "qux") {$2 = ""; print} else { print }; }' < file
7
  • If you want to keep the blank lines sed 's/qux//' < file
    – ojblass
    Apr 2, 2009 at 2:39
  • That awk solution doesn't change the file (in Cygwin at least).
    – paxdiablo
    Apr 2, 2009 at 2:51
  • Never mind, I see the problem, it was the second ==, I've fixed it for ya'.
    – paxdiablo
    Apr 2, 2009 at 2:53
  • @Pax: if I want to do in-place replacement to the file how could I do it? And in AWK how do you print with tab delimited? Now it prints with space delimited.
    – neversaint
    Apr 2, 2009 at 3:03
  • @foolishbrat sed and awk don't do in place edits; you can use perl for that, or super sed (ssed). Otherwise the standard thing to do is use a temporary file.
    – guns
    Apr 2, 2009 at 3:07
1
 nawk '{ gsub( /qux/, " " ); print }' filename

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.