user10480468
user10480468

Reputation:

Awk to Add [ ] in special characters

I am trying to add [] if the column contains special characters or number except for a comma , at the end. The first line needs to be as it is in the file.

Current:

CREATE TEST 
a,
b,
23_test,

Expectation:

CREATE TEST 
a,
b,
[23_test],

Upvotes: 0

Views: 378

Answers (3)

Claes Wikner
Claes Wikner

Reputation: 1517

awk '{sub(/23_test/,"[23_test]")}1' file

CREATE TEST 
a,
b,
[23_test],

Upvotes: 0

user10480468
user10480468

Reputation:

awk 'NR>1 && /[-0-9_+. ]/ {$0 = "[" gensub(",$", "", 1) "],"} {print}' <filename.out> | sed 's/, ]/]/'

Upvotes: 0

tshiono
tshiono

Reputation: 22042

Assuming that the special characters are digits, whitespaces, minus signs, plus signs, dots, and underscores (please modify the patten according to your definition), how about:

awk 'NR>1 && /[-0-9_+. ]/ {$0 = "[" gensub(",$", "", 1) "],"} {print}' input.txt

If you can be specific that the special characters are any characters other than alphabets and commas, try instead:

awk 'NR>1 && /[^a-zA-Z,]/ {$0 = "[" gensub(",$", "", 1) "],"} {print}' input.txt

Hope this helps.

Upvotes: 1

Related Questions