How to remove whitespace from specifc line?

2

Say I have a file structured so:

X sequence 1 is this

ABCDE FGH HIJ

X sequence 2 is this

ABCDE FGH HIJ

How would I conditionally remove whitespace? I know the snippet below will remove all whitespace. How would I be able to remove whitespace only on the lines beginning with X?

sed 's/ //g' 

I also had seen

 '/^startswith

been used, but can't seem to tie them together to work.

Thanks.

TW93

Posted 2017-03-02T11:24:04.733

Reputation: 123

Answers

3

In awk, the general syntax is address followed by a code block, where "address" is either a line number or a /regex/ or a comma-separated from,to range.

So if you want to match lines starting with X and apply a substitution to them:

/^X/ { gsub(/ /, ""); } { print; }

(The 2nd block is addressless, so it prints all lines.)

sed's syntax is similar, except the commands are shorter (s/…/…/ for substitution) and single-command blocks don't need the braces. So the same task can be performed in sed using:

/^X/ { s/ //g; }

or the shorter

/^X/ s/ //g

(Sed also doesn't need an explicit "print" block since printing is already the default there, unless -n is given. But it does have a print command p.)

user1686

Posted 2017-03-02T11:24:04.733

Reputation: 283 655

Excellent. I was doing similar, but over-complicating it and adding junk later one. Thank you for your help. – TW93 – 2017-03-02T11:30:09.907