0

Say I have a column of data like this:

sample123
sample456
samplexyz

I can easily add two new columns using:

sed -i "s/$/\t1.1\tC/" <file.txt>

Now it's:

sample123   1.1 C
sample456   1.1 C
samplexyz   1.1 C

Now say I append some new data at the bottom:

sample123   1.1 C
sample456   1.1 C
samplexyz   1.1 C
sampleNew1
sampleNew2
sampleNew3

If I try to append the new columns for this data, it appends to all rows, so now when I run:

sed -i "s/$/\t1.2\tA/" <file.txt>

It looks like:

sample123   1.1 C   1.2 A
sample456   1.1 C   1.2 A
samplexyz   1.1 C   1.2 A
sampleNew1  1.2 A
sampleNew2  1.2 A
sampleNew3  1.2 A

How do I add the columns where there are no other columns except the first one?

Paulo Tomé
  • 3,782

1 Answers1

3

Test first whether the current line has tab on it or not, and only do the substitution if it hasn't:

sed -i '/\t/!s/$/\t1.2\tA/' file

Here, we address all lines that does not contain a tab character using /\t/! and apply the substitution to those lines.

The above assumes GNU sed to be able to recognise \t as a tab character. Other sed implementations may need to use a literal tab character in place of \t. Other sed implementations may also handle the -i option differently from GNU sed (see "How can I achieve portability with sed -i (in-place editing)?").


Using awk:

awk -F "\t" 'BEGIN { OFS=FS } NF == 1 { $2 = "1.2"; $3 = "A" }; 1' file

This would test the number of tab-delimited fields, and if there is only a single field it would add a new second and third field before printing the line.

This would not change the file in-place. For that, use GNU awk like so:

awk -i inplace -F "\t" 'BEGIN { OFS=FS } NF == 1 { $2 = "1.2"; $3 = "A" }; 1' file

For more information about awk and in-place edits, see "How to permanently change a file using awk? ("in-place" edits, as with "sed -i")".

Kusalananda
  • 333,661