4

I am trying to write awk for a file I have. Example of the dataset is

S,CV0110,1235
S,1234
D,CQ120,3245
P,7894

Desired outcome is as follows (added empty field when the number of fields in a row is 2)

S,CV0110,1235
S,,1234
D,CQ120,3245
P,,7894

I tried this but it is adding value for all data rows instead of those that have 2 fields.

printf 'S,CV010,1235\r\n' | awk 'BEGIN{FS=OFS="fs"}{$n = $n OFS value}1'
1
  • 1
    So we can explain where you went wrong, what were you hoping that setting FS to "fs" would do? – Ed Morton Jan 28 at 1:52
6

Given

$ cat file
S,CV0110,1235
S,1234
D,CQ120,3245
P,7894

then

$ awk -F, 'BEGIN{OFS=FS} NF<3{$1 = $1 OFS} 1' file
S,CV0110,1235
S,,1234
D,CQ120,3245
P,,7894
4
sed '/,.*,/!s/,/,,/' file
  • /,.*,/! If line does not contain two commas,
  • s/,/,,/ Substitute the first comma by two commas.

This can be generalized to more fields. E.g., to add an empty field if some line is missing the 7th field,

sed -E '/,(.*,){5}/!s/,/,,/' file
2

Assuming the values en each column are always similar.

If a single letter at the start of the line is followed by 4 numbers and the line ends, add a comma:

sed '/^[A-Z],[0-9]\{4\}$/s/,/,,/' file

Output:

S,CV0110,1235
S,,1234
D,CQ120,3245
P,,7894

Your Answer

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

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