-1

how to replace special character in specific field?

INPUT

xxxx,11/2019,xxx

OUTPUT

xxxx,11,2019,xxx

As you see that am looking to replace / with , in $2 only.

How achieve that?

2
awk -F, -v OFS=, '{gsub(/\//,",",$2); print}'

This uses awk's gsub() function to do a global regexp search and replace on field 2.

If you want to replace only the first occurence of / in $2, use sub() rather than gsub().

NOTE: the default output field separator OFS is a space. You need to set it to , (same as the input field separator FS), otherwise the print will output all the fields with spaces separating them.

From the man page for GNU awk:

gsub(r, s [, t])

For each substring matching the regular expression r in the string t, substitute the string s, and return the number of substitutions.

If t is not supplied, use $0.

An & in the replacement text is replaced with the text that was actually matched.

Use \& to get a literal &. (This must be typed as \\&; see GAWK: Effective AWK Programming for a fuller discussion of the rules for &'s and backslashes in the replacement text of sub(), gsub(), and gensub().)

0

The command given in the previous answer can be much simpler. Tested and working fine.

Since changes need to be done in second column, I have added the same content in a second column and tested.

echo "echo "xxxx,11/2019,xxx xxxx,11/2019,xxx" " |
awk '{print gsub("/",",",$2);print $0}'  

Output:

xxxx,11/2019,xxx xxxx,11,2019,xxx

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.